-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathnumber-of-islands.cpp
68 lines (56 loc) · 1.67 KB
/
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
67
68
class Solution {
public:
void dfs(vector<vector<char>>& grid, int x, int y, int nr, int nc) {
if(x<0 || x >=nr || y<0 || y >=nc || grid[x][y] != '1') return;
grid[x][y] = '*';
dfs(grid, x+1, y, nr, nc);
dfs(grid, x-1, y, nr, nc);
dfs(grid, x, y+1, nr, nc);
dfs(grid, x, y-1, nr, nc);
}
int numIslands(vector<vector<char>>& grid) {
int res = 0;
int nr = grid.size();
if (!nr) return 0;
int nc = grid[0].size();
for(int r=0; r<nr; r++) {
for(int c=0; c<nc; c++) {
if(grid[r][c] == '1') {
res++;
dfs(grid, r, c, nr, nc);
}
}
}
return res;
}
};
// Complex One ::
// class Solution {
// public:
// int dirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};
// void DFS(vector<vector<char>>& board, int i, int j, int m, int n) {
// if (i < 0 || i == m || j < 0 || j == n || board[i][j] == '0') {
// return;
// }
// for (auto d : dirs) {
// int x = i + d[0], y = j + d[1];
// board[i][j] = '0';
// DFS(board, x, y, m, n);
// }
// }
// int numIslands(vector<vector<char>>& grid) {
// int nr = grid.size();
// if (!nr) return 0;
// int nc = grid[0].size();
// int num_islands = 0;
// for (int r = 0; r < nr; ++r) {
// for (int c = 0; c < nc; ++c) {
// if (grid[r][c] == '1') {
// ++num_islands;
// DFS(grid, r, c,nr,nc);
// }
// }
// }
// return num_islands;
// }
// };