-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathislands.cpp
51 lines (43 loc) · 1.27 KB
/
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
#include <bits/stdc++.h>
using namespace std;
class Solution
{
public:
vector<int> direction = {0, 1, 0, -1, 0};
int numIslands(vector<vector<char>> &grid)
{
int num = 0;
int m = grid.size();
int n = grid[0].size();
for (long i = 0; i < m; i++)
{
for (long j = 0; j < n; j++)
{
if (grid[i][j] == '1')
{
num++;
queue<pair<int, int>> q;
q.push({i, j});
while (!q.empty())
{
auto [u, v] = q.front();
q.pop();
for (long k = 0; k < 4; k++)
{
int nu, nv;
nu = u + direction[k];
nv = v + direction[k + 1];
if (nu < 0 || nu >= m || nv < 0 || nv >= n || grid[nu][nv] != '1')
{
continue;
}
grid[nu][nv] = '0';
q.emplace(nu, nv);
}
}
}
}
}
return num;
}
};