forked from codemistic/Data-Structures-and-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathNumber of Islands.cpp
43 lines (38 loc) · 949 Bytes
/
Number of Islands.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
class Solution {
public:
bool Isvisit(int i,int j,int n,int m, vector<vector<char>>&grid){
if(i >= 0 && i < n && j >= 0 && j < m && grid[i][j] == '1'){
return true;
}
return false;
}
void dfs(int i,int j,int n,int m, vector<vector<char>>&grid){
grid[i][j] = '0';
if(Isvisit(i+1,j,n,m,grid)){
dfs(i+1,j,n,m,grid);
}
if(Isvisit(i-1,j,n,m,grid)){
dfs(i-1,j,n,m,grid);
}
if(Isvisit(i,j+1,n,m,grid)){
dfs(i,j+1,n,m,grid);
}
if(Isvisit(i,j-1,n,m,grid)){
dfs(i,j-1,n,m,grid);
}
}
int numIslands(vector<vector<char>>& grid) {
int n = grid.size();
int m = grid[0].size();
int cnt = 0;
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++){
if(grid[i][j] == '1'){
dfs(i,j,n,m,grid);
cnt++;
}
}
}
return cnt;
}
};