Skip to content

Commit 59c1117

Browse files
Merge pull request #162 from shivamsingh67/patch-3
Create Number of Islands.cpp
2 parents 0142a26 + f8c839b commit 59c1117

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed
Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
class Solution {
2+
public:
3+
4+
bool Isvisit(int i,int j,int n,int m, vector<vector<char>>&grid){
5+
if(i >= 0 && i < n && j >= 0 && j < m && grid[i][j] == '1'){
6+
return true;
7+
}
8+
return false;
9+
}
10+
11+
void dfs(int i,int j,int n,int m, vector<vector<char>>&grid){
12+
grid[i][j] = '0';
13+
14+
if(Isvisit(i+1,j,n,m,grid)){
15+
dfs(i+1,j,n,m,grid);
16+
}
17+
if(Isvisit(i-1,j,n,m,grid)){
18+
dfs(i-1,j,n,m,grid);
19+
}
20+
if(Isvisit(i,j+1,n,m,grid)){
21+
dfs(i,j+1,n,m,grid);
22+
}
23+
if(Isvisit(i,j-1,n,m,grid)){
24+
dfs(i,j-1,n,m,grid);
25+
}
26+
}
27+
28+
int numIslands(vector<vector<char>>& grid) {
29+
int n = grid.size();
30+
int m = grid[0].size();
31+
int cnt = 0;
32+
33+
for(int i = 0; i < n; i++){
34+
for(int j = 0; j < m; j++){
35+
if(grid[i][j] == '1'){
36+
dfs(i,j,n,m,grid);
37+
cnt++;
38+
}
39+
}
40+
}
41+
return cnt;
42+
}
43+
};

0 commit comments

Comments
 (0)