forked from ShyrenMore/InterviewPrep
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathno_of_islands.cpp
63 lines (55 loc) · 1.79 KB
/
no_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
#include <vector>
#include <queue>
#include <iostream>
using namespace std;
class Solution
{
private:
void bfs(int row, int col, vector<vector<int>> &visited, vector<vector<char>> &grid, int delta_row[], int delta_col[])
{
int n = grid.size();
int m = grid[0].size();
visited[row][col] = 1;
queue<pair<int, int>> q;
q.push({row, col});
while (!q.empty())
{
int r = q.front().first;
int c = q.front().second;
q.pop();
for (int i = 0; i < 4; i++)
{
int neighbour_row = r + delta_row[i];
int neighbour_col = c + delta_col[i];
// for each neighbour check boundary
if (neighbour_row >= 0 && neighbour_row < n && neighbour_col >= 0 && neighbour_col < m)
{
// check for same color and prev visited
if (grid[neighbour_row][neighbour_col] == '1' && !visited[neighbour_row][neighbour_col])
{
visited[neighbour_row][neighbour_col] = 1;
q.push({neighbour_row, neighbour_col});
}
}
}
}
}
public:
int numIslands(vector<vector<char>> &grid)
{
int n = grid.size();
int m = grid[0].size();
vector<vector<int>> visited(n, vector<int>(m, 0));
int ans = 0;
int delta_row[] = {-1, 0, 1, 0};
int delta_col[] = {0, 1, 0, -1};
for (int r = 0; r < n; r++)
for (int c = 0; c < m; c++)
if (!visited[r][c] && grid[r][c] == '1')
{
++ans;
bfs(r, c, visited, grid, delta_row, delta_col);
}
return ans;
}
};