-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem_0695_maxAreaOfIsland.cc
110 lines (104 loc) · 2.44 KB
/
Problem_0695_maxAreaOfIsland.cc
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
#include <queue>
#include <stack>
#include <vector>
using namespace std;
class Solution
{
public:
static constexpr int direction[4][2] = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
int dfs(vector<vector<int>>& grid, int x, int y)
{
if (x < 0 || y < 0 || x == grid.size() || y == grid[0].size() || grid[x][y] != 1)
{
return 0;
}
grid[x][y] = 0;
int ans = 1;
for (int i = 0; i < 4; i++)
{
int nextx = x + direction[i][0];
int nexty = y + direction[i][1];
ans += dfs(grid, nextx, nexty);
}
return ans;
}
// dfs
int maxAreaOfIsland1(vector<vector<int>>& grid)
{
int ans = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
ans = std::max(ans, dfs(grid, i, j));
}
}
return ans;
}
// dfs + stack
int maxAreaOfIsland2(vector<vector<int>>& grid)
{
int ans = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
int cur = 0;
stack<std::pair<int, int>> st;
st.push({i, j});
while (!st.empty())
{
auto [x, y] = st.top();
st.pop();
if (x < 0 || y < 0 || x == grid.size() || y == grid[0].size() || grid[x][y] != 1)
{
continue;
}
++cur;
grid[x][y] = 0;
for (int index = 0; index < 4; index++)
{
int nextx = x + direction[index][0];
int nexty = y + direction[index][1];
st.push({nextx, nexty});
}
}
ans = std::max(ans, cur);
}
}
return ans;
}
// bfs
int maxAreaOfIsland3(vector<vector<int>>& grid)
{
int ans = 0;
for (int i = 0; i < grid.size(); i++)
{
for (int j = 0; j < grid[0].size(); j++)
{
int cur = 0;
queue<std::pair<int, int>> q;
q.push({i, j});
while (!q.empty())
{
auto [x, y] = q.front();
q.pop();
if (x < 0 || y < 0 || x == grid.size() || y == grid[0].size() || grid[x][y] != 1)
{
continue;
}
++cur;
grid[x][y] = 0;
for (int index = 0; index < 4; index++)
{
int nextx = x + direction[index][0];
int nexty = y + direction[index][1];
q.push({nextx, nexty});
}
}
ans = std::max(ans, cur);
}
}
return ans;
}
};