/
200.number-of-islands.cpp
66 lines (54 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
66
/*
* @lc app=leetcode id=200 lang=cpp
*
* [200] Number of Islands
*/
// @lc code=start
class Solution
{
vector<pair<int, int>> dirs = {{1, 0}, {0, 1}, {-1, 0}, {0, -1}};
public:
int numIslands(vector<vector<char>> &grid)
{
// either bfs ad dfs works
// this is the bfs solution
const int m = grid.size();
if (m == 0)
return 0;
const int n = grid[0].size();
int count = 0;
// find the next 1
for (int i = 0; i < m; ++i)
{
for (int j = 0; j < n; ++j)
{
if (grid[i][j] == '1')
{
count += 1;
//do bfs here
queue<pair<int, int>> q; //{pos}
q.push({i, j});
grid[i][j] = '#';
while (!q.empty())
{
auto [curr_x, curr_y] = q.front();
q.pop();
for (auto &dir : dirs)
{
int n_x = curr_x + dir.first;
int n_y = curr_y + dir.second;
if (n_x < 0 || n_y < 0 || n_x >= m || n_y >= n)
continue;
if (grid[n_x][n_y] != '1')
continue;
q.push({n_x, n_y});
grid[n_x][n_y] = '#';
} //for
} //while
}
} //for
} //for
return count;
}
};
// @lc code=end