-
Notifications
You must be signed in to change notification settings - Fork 307
/
Number of Islands.cpp
75 lines (69 loc) · 1.48 KB
/
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
//Given an m x n 2D binary grid grid which represents a map of '1's (land) and '0's (water), return the number of islands.
class Solution {
struct node{
int x;
int y;
node(int _x,int _y)
{
x=_x;
y=_y;
}
};
public:
int visited[1000][1000];
void bfs(int i,int j,int n,int m,vector<vector<char>>& grid)
{
queue<node>q;
q.push(node(i,j));
visited[i][j]=1;
cout<<i<<" "<<j<<endl;
while(!q.empty())
{
int a=q.front().x;
int b=q.front().y;
q.pop();
cout<<a<<" "<<b<<endl;
int ar1[4]={1,0,-1,0};
int ar2[4]={0,-1,0,1};
for(int k=0;k<4;k++)
{
int c=a+ar1[k];
int d=b+ar2[k];
if(c>=0 && c<n && d>=0 && d<m && visited[c][d]==0)
{
visited[c][d]=1;
q.push(node(c,d));
}
}
}
}
int numIslands(vector<vector<char>>& grid) {
int n=grid.size();
int m=grid[0].size();
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j]=='1')
{
visited[i][j]=0;
}
else{
visited[i][j]=1;
}
}
}
int count=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
if(grid[i][j]=='1' && visited[i][j]==0)
{
bfs(i,j,n,m,grid);
count++;
}
}
}
return count;
}};