Skip to content

Commit 0792232

Browse files
authored
Merge pull request kothariji#465 from MariaThomson/master
Added number of Islands program from leetcode
2 parents 2d32d03 + 074f987 commit 0792232

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

Tree/(Leet_Code)Number of Islands.cpp

+72
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
class Solution {
2+
struct node{
3+
int x;
4+
int y;
5+
node(int _x,int _y)
6+
{
7+
x=_x;
8+
y=_y;
9+
}
10+
};
11+
public:
12+
int visited[1000][1000];
13+
void bfs(int i,int j,int n,int m,vector<vector<char>>& grid)
14+
{
15+
queue<node>q;
16+
q.push(node(i,j));
17+
visited[i][j]=1;
18+
cout<<i<<" "<<j<<endl;
19+
while(!q.empty())
20+
{
21+
int a=q.front().x;
22+
int b=q.front().y;
23+
q.pop();
24+
cout<<a<<" "<<b<<endl;
25+
int ar1[4]={1,0,-1,0};
26+
int ar2[4]={0,-1,0,1};
27+
for(int k=0;k<4;k++)
28+
{
29+
int c=a+ar1[k];
30+
int d=b+ar2[k];
31+
32+
if(c>=0 && c<n && d>=0 && d<m && visited[c][d]==0)
33+
{
34+
visited[c][d]=1;
35+
q.push(node(c,d));
36+
}
37+
}
38+
}
39+
}
40+
int numIslands(vector<vector<char>>& grid) {
41+
int n=grid.size();
42+
int m=grid[0].size();
43+
44+
for(int i=0;i<n;i++)
45+
{
46+
for(int j=0;j<m;j++)
47+
{
48+
if(grid[i][j]=='1')
49+
{
50+
visited[i][j]=0;
51+
}
52+
else{
53+
visited[i][j]=1;
54+
}
55+
}
56+
}
57+
58+
int count=0;
59+
for(int i=0;i<n;i++)
60+
{
61+
for(int j=0;j<m;j++)
62+
{
63+
if(grid[i][j]=='1' && visited[i][j]==0)
64+
{
65+
bfs(i,j,n,m,grid);
66+
count++;
67+
}
68+
}
69+
}
70+
71+
return count;
72+
}};

0 commit comments

Comments
 (0)