forked from algorithm023/algorithm023
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumIslands.cpp
More file actions
83 lines (76 loc) · 2.69 KB
/
Copy pathnumIslands.cpp
File metadata and controls
83 lines (76 loc) · 2.69 KB
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
#include <vector>
/*解法:
dfs:时间复杂度O(M*N),空间复杂度O(M*N)
BFS:时间复杂度O(M*N),空间复杂度Omin(M,N)*/
using namespace std;
void dfs(vector<vector<char>>& grid, int row, int col) {
if (grid.size() <= row || row < 0
|| col >= grid[0].size() || col < 0) {
return;
}
if (grid[row][col] != '1') return;
grid[row][col] = '2';//这样就不用加visited了
dfs(grid, row, col - 1);
dfs(grid, row, col + 1);
dfs(grid, row - 1, col);
dfs(grid, row + 1, col);
}
//bfs方法
//int numIslands(vector<vector<char>>& grid) {
// int numIsland = 0;
// queue<std::pair<int, int>> record;
// for (int row = 0; row < grid.size(); row++) {
// for (int col = 0; col < grid[row].size(); col++) {
// if (grid[row][col] == '1') {
// numIsland++;
// record.push(std::make_pair(row, col));
// while (!record.empty()) {
// std::pair<int, int> pair = record.front();
// grid[pair.first][pair.second] = '2';
// record.pop();
// if (isIsland(grid, pair.first, pair.second + 1)) {
// record.push(std::make_pair(pair.first, pair.second + 1));
// grid[pair.first][pair.second + 1] = '2';
// }
//
// if (isIsland(grid, pair.first, pair.second - 1)) {
// record.push(std::make_pair(pair.first, pair.second - 1));
// grid[pair.first][pair.second - 1] = '2';
// }
//
// if (isIsland(grid, pair.first + 1, pair.second)) {
// record.push(std::make_pair(pair.first + 1, pair.second));
// grid[pair.first + 1][pair.second] = '2';
// }
//
// if (isIsland(grid, pair.first - 1, pair.second)) {
// record.push(std::make_pair(pair.first - 1, pair.second));
// grid[pair.first - 1][pair.second] = '2';
// }
// }
// }
// }
// }
// return numIsland;
//}
int numIslands(vector<vector<char>>& grid) {
int numIsland = 0;
for (int i = 0; i < grid.size(); i++) {
for (int j = 0; j < grid[i].size(); j++) {
if (grid[i][j] == '1') {
numIsland++;
dfs(grid, i, j);
}
}
}
return numIsland;
}
void main()
{
vector<vector<char>> grid;
grid.push_back({ '1', '1', '1', '1', '0' });
grid.push_back({ '1', '1', '0', '1', '0' });
grid.push_back({ '1', '1', '0', '0', '0' });
grid.push_back({ '0', '0', '0', '0', '0' });
numIslands(grid);
}