-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path200. Number of Islands.cpp
65 lines (55 loc) · 1.63 KB
/
200. 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
class Solution {
private:
void bfs(int r, int c, vector<vector<char>>& grid, vector<vector<bool> >&vis)
{
vis[r][c] = 1;
queue<pair<int, int> > q;
q.push({r, c});
int n = grid.size();
int m = grid[0].size();
while(!q.empty())
{
int row = q.front().first;
int col = q.front().second;
q.pop();
//traverse all it's neighbours and mark them if it's a land
if(row-1 >= 0 && !vis[row-1][col] && grid[row-1][col] == '1')
{
q.push({row-1, col});
vis[row-1][col] = 1;
}
if(row+1 < n && !vis[row+1][col] && grid[row+1][col] == '1')
{
q.push({row+1, col});
vis[row+1][col] = 1;
}
if(col-1 >= 0 && !vis[row][col-1] && grid[row][col-1] == '1')
{
q.push({row, col-1});
vis[row][col-1] = 1;
}
if(col+1 < m && !vis[row][col+1] && grid[row][col+1] == '1')
{
q.push({row, col+1});
vis[row][col+1] = 1;
}
}
}
public:
int numIslands(vector<vector<char>>& grid) {
int n = grid.size();
int m = grid[0].size();
vector<vector<bool> > vis (n, vector<bool>(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, grid, vis);
}
}
}
return cnt;
}
};