[leetcode]695. Max Area of Island
Analysis
周五~—— [ummmm~]
Given a non-empty 2D array grid of 0’s and 1’s, an island is a group of 1’s (representing land) connected 4-directionally (horizontal or vertical.) You may assume all four edges of the grid are surrounded by water. Find the maximum area of an island in the given 2D array. (If there is no island, the maximum area is 0.) DFS~
Implement
class Solution {
public:
int maxAreaOfIsland(vector<vector<int>>& grid) {
int w = grid.size();
int l = grid[
0].size();
visit.resize(w);
for(int i=
0; i<w; i++){
visit[i].resize(l);
for(int j=
0; j<l; j++)
visit[i][j] =
0;
}
int res =
0;
for(int i=
0; i<w; i++){
for(int j=
0; j<l; j++){
if(grid[i][j]==
1 && !visit[i][j])
res = max(res, DFS(grid, i, j));
}
}
return res;
}
int DFS(vector<vector<int>>& grid, int i, int j){
if(i>=
0 && i<grid.size() && j>=
0 && j<grid[
0].size() && grid[i][j]==
1 && !visit[i][j]){
visit[i][j] =
1;
return 1 + DFS(grid, i-
1, j) + DFS(grid, i+
1, j) + DFS(grid, i, j-
1) + DFS(grid, i, j+
1);
}
return 0;
}
private:
vector<vector<int>> visit;
};