forked from rising-entropy/Leetcode-Questions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNumber_of_Islands.cpp
More file actions
27 lines (27 loc) · 826 Bytes
/
Number_of_Islands.cpp
File metadata and controls
27 lines (27 loc) · 826 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
class Solution {
public:
int numIslands(vector<vector<char>>& grid) {
int m = grid.size(), n = m ? grid[0].size() : 0, islands = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1') {
islands++;
eraseIslands(grid, i, j);
}
}
}
return islands;
}
private:
void eraseIslands(vector<vector<char>>& grid, int i, int j) {
int m = grid.size(), n = grid[0].size();
if (i < 0 || i == m || j < 0 || j == n || grid[i][j] == '0') {
return;
}
grid[i][j] = '0';
eraseIslands(grid, i - 1, j);
eraseIslands(grid, i + 1, j);
eraseIslands(grid, i, j - 1);
eraseIslands(grid, i, j + 1);
}
};