-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0200.NumberOfIslands.cpp
More file actions
36 lines (30 loc) · 872 Bytes
/
Copy path0200.NumberOfIslands.cpp
File metadata and controls
36 lines (30 loc) · 872 Bytes
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
class Solution {
public:
void expandIsland(vector<vector<char>>& grid, int x, int y) {
// Check if valid island.
if (x < 0 || y < 0 || y >= grid.size() || x >= grid[y].size() || grid[y][x] != '1') return;
// Update grid data, as to not repeat.
grid[y][x] = '2';
// Expand in all directions.
static const int checks[][2] = {
{ -1, 0 }, { +1, 0 },
{ 0, -1 }, { 0, +1 },
};
for (int i = 0; i < sizeof(checks) / sizeof(*checks); i++)
expandIsland(grid, x + checks[i][0], y + checks[i][1]);
}
int numIslands(vector<vector<char>>& grid) {
// Get island count.
int islandCount = 0;
for (int y = 0; y < grid.size(); y++) {
for (int x = 0; x < grid[y].size(); x++) {
// Ignore if not land.
if (grid[y][x] != '1') continue;
// Expand island.
expandIsland(grid, x, y);
islandCount++;
}
}
return islandCount;
}
};