-
Notifications
You must be signed in to change notification settings - Fork 0
/
200.number-of-islands.cpp
62 lines (59 loc) · 1.54 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
/*
* @lc app=leetcode id=200 lang=cpp
*
* [200] Number of Islands
*/
// @lc code=start
// #include "helper.h"
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int numOfIslands = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[0].size(); j++) {
if (IsLand(grid[i][j]) && !IsVisited(grid[i][j])) {
numOfIslands++;
traverse(grid, i, j);
}
}
}
return numOfIslands;
}
void traverse(vector<vector<char>>& grid, int i, int j)
{
queue<pair<int, int>> q;
constexpr int dx[] = {0, 1, 0, -1};
constexpr int dy[] = {1, 0, -1, 0};
q.push({i, j});
grid[i][j] = SetVisited(grid[i][j]);
while (!q.empty()) {
pair<int, int> p = q.front();
q.pop();
for (int k = 0; k < 4; k++) {
int x = p.first + dx[k];
int y = p.second + dy[k];
if (x < 0 || x >= grid.size() || y < 0 || y >= grid[0].size()) {
continue;
}
if (IsLand(grid[x][y]) && !IsVisited(grid[x][y])) {
q.push({x, y});
grid[x][y] = SetVisited(grid[x][y]);
}
}
}
}
private:
bool IsLand(int v)
{
return (v & 1) == 1;
}
bool IsVisited(int v)
{
return (v & 2) == 2;
}
int SetVisited(int v)
{
return v | 2;
}
};
// @lc code=end