-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy path200
49 lines (46 loc) · 1.15 KB
/
200
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
44
45
46
47
48
49
class Solution {
public:
void find(int i,int j,vector<vector<char>>& grid,vector<vector<int>>& vis){
int n=grid.size();
int m=grid[0].size();
if(i>n-1 || i<0 || j<0 || j>m-1 || vis[i][j]==1)
return;
vis[i][j]=1;
if(i+1<n){
if(grid[i+1][j]=='1' && vis[i+1][j]==0){
find(i+1,j,grid,vis);
}
}
if(i-1>=0){
if(grid[i-1][j]=='1' && vis[i-1][j]==0){
find(i-1,j,grid,vis);
}
}
if(j+1<m){
if(grid[i][j+1]=='1' && vis[i][j+1]==0){
find(i,j+1,grid,vis);
}
}
if(j-1>=0){
if(grid[i][j-1]=='1' && vis[i][j-1]==0){
find(i,j-1,grid,vis);
}
}
return ;
}
int numIslands(vector<vector<char>>& grid) {
int n=grid.size();
int m=grid[0].size();
vector<vector<int>> vis(n,vector<int>(m,0));
int c=0;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
if(grid[i][j]=='1' && vis[i][j]==0){
find(i,j,grid,vis);
c++;
}
}
}
return c;
}
};