一、题目
二、代码
class Solution
{
int[][] position = {{-1,0},{1,0},{0,-1},{0,1}};
public int dfs(int[][]grid, int row, int col ,int mark)
{
int ans = 0;
grid[row][col] = mark;
for(int[] current: position)
{
int curRow = row +current[0] , curCol = col +current[1];
if(curRow < 0 || curRow >= grid.length || curCol <0 || curCol >= grid.length) continue;
if(grid[curRow][curCol] == 1)
{
ans += 1+ dfs(grid, curRow ,curCol ,mark);
}
}
return ans;
}
public int largestIsland(int[][] grid)
{
int ans = Integer.MIN_VALUE, size = grid.length, mark = 2;
Map<Integer,Integer> getSize = new HashMap<>();
for(int row = 0; row <size; row++)
{
for(int col = 0; col<size; col++)
{
if(grid[row][col]==1)
{
int areaSize = 1 + dfs(grid, row , col, mark);
getSize.put(mark++, areaSize);
}
}
}
for(int row = 0; row<size;row++)
{
for(int col =0 ; col<size; col++)
{
if(grid[row][col]!=0) continue;
Set<Integer> hashSet = new HashSet<>();
int curSize = 1;
for(int[] current: position)
{
int curRow = row + current[0],curCol = col + current[1];
if(curRow< 0 ||curRow >= grid.length ||curCol<0||curCol >= grid.length) continue;
int curMark = grid[curRow][curCol];
if(hashSet.contains(curMark) || !getSize.containsKey(curMark)) continue;
hashSet.add(curMark);
curSize += getSize.get(curMark);
}
ans = Math.max(ans,curSize);
}
}
return ans == Integer.MIN_VALUE ? size*size :ans;
}
}
三、运行结果