LeetCode 827题
也是递归
class Solution {
boolean isChanged = false;
int count = 0;
int resNum = 0;
Map<Integer, Integer> map = new HashMap<>();
public int largestIsland(int[][] grid) {
int flag = 2;
int row = grid.length;
int col = grid[0].length;
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(grid[i][j] == 1) {
count = 0;
dfs(grid, i, j, flag++);
if(resNum < count){
resNum = count;
}
map.put(flag-1, count);
}
}
}
for(int i = 0; i < row; i++) {
for(int j = 0; j < col; j++) {
if(grid[i][j] == 0) {
isChanged = true;
cal(grid, i, j);
}
}
}
if(!isChanged){
return resNum;
}
return resNum+1;
}
public void cal(int[][] grid, int row, int col){
List<Integer> list = new ArrayList<>();
int size = 0;
if(row > 0 && grid[row-1][col] != 0 && !list.contains(grid[row-1][col])) {//向上
size += map.get(grid[row-1][col]);
list.add(grid[row-1][col]);
}
if(col > 0 && grid[row][col-1] != 0 && !list.contains(grid[row][col-1])) {//向左
size += map.get(grid[row][col-1]);
list.add(grid[row][col-1]);
}
if(col+1 < grid[0].length && grid[row][col+1] != 0 && !list.contains(grid[row][col+1])) {//向右
size += map.get(grid[row][col+1]);
list.add(grid[row][col+1]);
}
if(row+1 < grid.length && grid[row+1][col] != 0 && !list.contains(grid[row+1][col])) {//向下
size += map.get(grid[row+1][col]);
list.add(grid[row+1][col]);
}
if(resNum < size){
resNum = size;
}
}
public void dfs(int[][] grid, int row, int col, int flag) {
grid[row][col] = flag;
count++;
if(row > 0 && grid[row-1][col] == 1) {//向上
dfs(grid, row-1, col, flag);
}
if(col > 0 && grid[row][col-1] == 1) {//向左
dfs(grid, row, col-1, flag);
}
if(col+1 < grid[0].length && grid[row][col+1] == 1) {//向右
dfs(grid, row, col+1, flag);
}
if(row+1 < grid.length && grid[row+1][col] == 1) {//向下
dfs(grid, row+1, col, flag);
}
}
}