vault backup: 2022-07-16 08:59:20
This commit is contained in:
parent
21c5c54fbc
commit
6e0d9d8176
|
@ -68,6 +68,11 @@ We keep track of pile we visited, using:
|
|||
- an 2-d bool vector visited(which is the one I'm using)
|
||||
- change the value of pile to 0
|
||||
|
||||
and check for:
|
||||
- x, y is not OOB
|
||||
- x, y is in a island -> (value == 1)
|
||||
- x, y is not visited (see above)
|
||||
|
||||
And for each unvisited pile, run DFS or BFS to check the size, and keep track of max size with a variable
|
||||
|
||||
### Solution
|
||||
|
@ -204,3 +209,44 @@ public:
|
|||
```
|
||||
|
||||
DFS recursive
|
||||
```cpp
|
||||
class Solution {
|
||||
// DFS recursive
|
||||
int getSize(vector<vector<int>> &grid, int m, int n, int x, int y,
|
||||
vector<vector<bool>> &visited) {
|
||||
if (x >= 0 && x < m && y >= 0 && y < n && !visited[x][y] &&
|
||||
grid[x][y] == 1) {
|
||||
visited[x][y] = true;
|
||||
return 1 + getSize(grid, m, n, x + 1, y, visited) +
|
||||
getSize(grid, m, n, x - 1, y, visited) +
|
||||
getSize(grid, m, n, x, y + 1, visited) +
|
||||
getSize(grid, m, n, x, y - 1, visited);
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
public:
|
||||
int maxAreaOfIsland(vector<vector<int>> &grid) {
|
||||
int m = grid.size(), n = grid[0].size();
|
||||
int maxSize = 0;
|
||||
|
||||
vector<vector<bool>> visited;
|
||||
for (int i = 0; i < m; i++) {
|
||||
visited.push_back({});
|
||||
for (int j = 0; j < n; j++) {
|
||||
visited.back().push_back(false);
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < m; i++) {
|
||||
for (int j = 0; j < n; j++) {
|
||||
if (grid[i][j] == 1 && !visited[i][j]) {
|
||||
maxSize = max(maxSize, getSize(grid, m, n, i, j, visited));
|
||||
}
|
||||
}
|
||||
}
|
||||
return maxSize;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in a new issue