示例 1:
示例 2:
class Solution {public int maxAreaOfIsland(int[][] grid) {int max = 0;for(int i = 0;ifor(int j = 0;jif(grid[i][j] == 1){max = Math.max(max,dfs(i,j,grid));}}}return max;}public int dfs(int i,int j,int[][] grid){if(i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || grid[i][j] == 0){return 0;}grid[i][j] = 0;int count = 1;count += dfs(i + 1,j,grid);count += dfs(i,j + 1,grid);count += dfs(i - 1,j,grid);count += dfs(i,j - 1,grid);return count;}
}
int dfs(int** grid,int i,int j,int row,int col)
{if(i < 0 || i >= row || j < 0 || j >= col || grid[i][j] == 0){return 0;}grid[i][j] = 0;int count = 1;count += dfs(grid,i + 1,j,row,col);count += dfs(grid,i,j + 1,row,col);count += dfs(grid,i - 1,j,row,col);count += dfs(grid,i,j - 1,row,col);return count;
}int maxAreaOfIsland(int** grid, int gridSize, int* gridColSize)
{int row = gridSize;int col = gridColSize[0];int res = 0;for(int i = 0;ifor(int j = 0;j res = fmax(res,dfs(grid,i,j,row,col));}}return res;
}
class Solution:def maxAreaOfIsland(self, grid: List[List[int]]) -> int:def dfs(grid,i,j):if i < 0 or i >= len(grid) or j < 0 or j >= len(grid[0]) or grid[i][j] == 0:return 0grid[i][j] = 0count = 1count += dfs(grid,i + 1,j)count += dfs(grid,i,j + 1)count += dfs(grid,i - 1,j)count += dfs(grid,i,j - 1)return countres = 0for i in range(len(grid)):for j in range(len(grid[0])):if grid[i][j] == 1:res = max(res,dfs(grid,i,j))return res
class Solution {
public:int dfs(vector>& grid,int i,int j){if(i < 0 || i >= grid.size() || j < 0 || j >= grid[0].size() || grid[i][j] == 0){return 0;}grid[i][j] = 0;int count = 1;count += dfs(grid,i + 1,j);count += dfs(grid,i,j + 1);count += dfs(grid,i - 1,j);count += dfs(grid,i,j - 1);return count;}int maxAreaOfIsland(vector>& grid) {int res = 0;for(int i = 0;ifor(int j = 0;jif(grid[i][j] == 1){res = max(res,dfs(grid,i,j));}}}return res;}
};
Java语言版
C语言版
Python语言版
C++语言版
上一篇:javaSE系列之类与对象
下一篇:Spring工厂基本流程