-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFind the number of islands.cpp
42 lines (42 loc) · 1.34 KB
/
Find the 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
private:
void bfs(int i,int j, vector<vector<int>>&vis,vector<vector<char>>&grid){
vis[i][j] = 1;
queue<pair<int,int>>q;
q.push({i,j});
int n = grid.size();
int m = grid[0].size();
while(!q.empty()){
int row = q.front().first;
int col = q.front().second;
q.pop();
for(int delrow = -1; delrow<=1; delrow++){
for(int delcol=-1; delcol<=1; delcol++){
int nrow = row + delrow;
int ncol = col + delcol;
if(nrow >=0 && nrow < n && ncol >=0 && ncol < m && !vis[nrow][ncol]
&& grid[nrow][ncol] == '1'){
vis[nrow][ncol] = 1;
q.push({nrow,ncol});
}
}
}
}
}
public:
// Function to find the number of islands.
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 cnt =0;
for(int i=0; i<n; i++){
for(int j=0; j<m; j++){
if(!vis[i][j] && grid[i][j] == '1'){
cnt++;
bfs(i,j,vis,grid);
}
}
}
return cnt;
// Code here
}