forked from kamyu104/LeetCode-Solutions
-
Notifications
You must be signed in to change notification settings - Fork 1
/
max-area-of-island.cpp
35 lines (33 loc) · 1.04 KB
/
max-area-of-island.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
// Time: O(m * n)
// Space: O(m * n), the max depth of dfs may be m * n
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int result = 0;
for (int i = 0; i < grid.size(); ++i) {
for (int j = 0; j < grid[0].size(); ++j) {
int area = 0;
if (dfs(i, j, &grid, &area)) {
result = max(result, area);
}
}
}
return result;
}
private:
bool dfs(const int i, const int j, vector<vector<int>> *grid, int *area) {
static const vector<pair<int, int>> directions{{-1, 0}, { 1, 0},
{ 0, 1}, { 0, -1}};
if (i < 0 || i >= grid->size() ||
j < 0 || j >= (*grid)[0].size() ||
(*grid)[i][j] <= 0) {
return false;
}
(*grid)[i][j] *= -1;
++(*area);
for (const auto& d : directions) {
dfs(i + d.first, j + d.second, grid, area);
}
return true;
}
};