/*
* @lc app=leetcode id=695 lang=cpp
*
* [695] Max Area of Island
*/
// @lc code=start
class Solution {
public:
int dfs(int x,int y, vector<vector<int>>& color, vector<int>& dirx, vector<int>& diry, vector<vector<int>>& grid){
int sum = 1;
color[x][y] = 1;
for(int i=0;i<4;i++){
if(color[x+dirx[i]][y+diry[i]] == 1) continue;
if(grid[x+dirx[i]-1][y+diry[i]-1] == 0) continue;
sum += dfs(x+dirx[i], y+diry[i], color, dirx, diry, grid);
}
return sum;
}
int maxAreaOfIsland(vector<vector<int>>& grid) {
int N = grid.size();
if(N == 0) return 0;
int M = grid[0].size();
vector<vector<int>> color(N+2, vector<int>(M+2, 0));
int ans = 0;
vector<int> dirx = {-1,0,1,0};
vector<int> diry = {0,-1,0,1};
for(int i=0;i<N+2;i++) color[i][0] = color[i][M+1] = 1;
for(int j=0;j<M+2;j++) color[0][j] = color[N+1][j] = 1;
for(int i=0;i<N;i++){
for(int j=0;j<M;j++){
if(grid[i][j] == 0) continue;
if(color[i+1][j+1] == 1) continue;
ans = max(ans, dfs(i+1,j+1,color, dirx, diry, grid));
}
}
return ans;
}
};
// @lc code=end
No.264 - LeetCode[695] Max Area of Island - 裸的dfs
最新推荐文章于 2024-09-01 11:38:54 发布