-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
114 lines (99 loc) · 3 KB
/
main.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
#include <iostream>
#include <queue>
using namespace std;
class Solution {
private:
int m, n;
vector<vector<bool>> visited;
void dfs(vector<vector<char>> &grid, int sx, int sy) {
queue<pair<int, int>> q;
const int dx[4] = {-1, 0, 0, 1};
const int dy[4] = {0, -1, 1, 0};
q.push({sx, sy});
visited[sx][sy] = true;
while (!q.empty()) {
// 第一步:取队头
int x = q.front().first;
int y = q.front().second;
q.pop();
// 第二步:扩展队头
for (int i = 0; i < 4; i++) {
int nx = x + dx[i];
int ny = y + dy[i];
if (nx < 0 || nx >= m || ny < 0 || ny >= n) {
continue;
}
if (grid[nx][ny] != '1')continue;
if (visited[nx][ny])continue;
q.push({nx, ny});
visited[nx][ny] = true;
}
}
}
void dfs2(vector<vector<char>> &grid, int sx, int sy) {
int m = grid.size();
int n = grid[0].size();
if (sx < 0 || sx >= m || sy < 0 || sy >= n || grid[sx][sy] == '0' || visited[sx][sy]) {
return;
}
visited[sx][sy] = true;
dfs2(grid, sx - 1, sy);
dfs2(grid, sx + 1, sy);
dfs2(grid, sx, sy - 1);
dfs2(grid, sx, sy + 1);
}
public:
int numIslands(vector<vector<char>> &grid) {
this->m = grid.size();
this->n = grid[0].size();
visited = vector<vector<bool>>(m, vector<bool>(n, false));
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1' && !visited[i][j]) {
ans++;
dfs(grid, i, j);
}
}
}
return ans;
}
int numIslands2(vector<vector<char>> &grid) {
int m = grid.size();
int n = grid[0].size();
visited = vector<vector<bool>>(m, vector<bool>(n, false));
int ans = 0;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == '1' && !visited[i][j]) {
ans++;
dfs2(grid, i, j);
}
}
}
return ans;
}
};
int main() {
Solution s;
vector<vector<char>> grid = {
{'1', '1', '1', '1', '0'},
{'1', '1', '0', '1', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '0', '0', '0'}};
int ans = s.numIslands(grid);
cout << ans << endl;
vector<vector<char>> grid2 = {
{'1', '1', '0', '0', '0'},
{'1', '1', '0', '0', '0'},
{'0', '0', '1', '0', '0'},
{'0', '0', '0', '1', '1'}};
ans = s.numIslands(grid2);
cout << ans << endl;
cout << "==========" << endl;
int ans1 = s.numIslands2(grid);
cout << ans1 << endl;
ans1 = s.numIslands2(grid2);
cout << ans1 << endl;
return 0;
}