一共有3种方法
- 递归方法 + 深度优先遍历
//递归实现深度优先遍历
public int dfs(int[][] grid, int i, int j){
int area = 0;
//上下左右四个移动方向
int[][] move_array = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
//数组越界或者该点为0,就返回0
if(i < 0 || j < 0 || i >= grid.length || j >= grid[0].length || grid[i][j] == 0)
return 0;
//访问过的点就置0
grid[i][j] = 0;
++area;
for(int[] x : move_array){
area += dfs(grid, i + x[0], j + x[1]);
}
return area;
}
public int maxAreaOfIsland(int[][] grid) {
int max = 0;
int m = grid.length;
int n = grid[0].length;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
max = Math.max(max, dfs(grid, i, j));
}
}
return max;
}
2. 栈 + 深度优先遍历 (非常重要,要加深理解)
//栈方法实现深度优先遍历
public static int maxAreaOfIsland(int[][] grid) {
int max = 0;
int m = grid.length;
int n = grid[0].length;
//用栈实现深度优先遍历
Deque<int[]> stack = new LinkedList<>();
//上下左右四个移动方向
int[][] move_array = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
stack.add(new int[]{i, j});
int area = 0;
while (!stack.isEmpty()){
int x = stack.peek()[0];
int y = stack.pop()[1];
//数组越界或者该点为0,就继续下一个循环
if(x < 0 || y < 0 || x >= m || y >= n || grid[x][y] == 0)
continue;
//访问过的点就置0
grid[x][y] = 0;
++area;
//上下左右四个方向都要访问
for(int[] move : move_array){
stack.add(new int[]{x + move[0], y + move[1]});
}
}
max = Math.max(max, area);
}
}
return max;
}
- 队列 + 广度优先遍历
//队列方法实现广度优先遍历
public int maxAreaOfIsland(int[][] grid) {
int max = 0;
int m = grid.length;
int n = grid[0].length;
//用队列实现广度优先遍历
Deque<int[]> queue = new LinkedList<>();
//上下左右四个移动方向
int[][] move_array = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
queue.addLast(new int[]{i, j});
int area = 0;
while (!queue.isEmpty()){
int size = queue.size();
for(int t = 0; t <size; t++){
int x = queue.peekFirst()[0];
int y = queue.removeFirst()[1];
//数组越界或者该点为0,就继续下一个循环
if(x < 0 || y < 0 || x >= m || y >= n || grid[x][y] == 0)
continue;
//访问过的点就置0
grid[x][y] = 0;
++area;
//上下左右四个方向都要访问
for(int[] move : move_array){
queue.add(new int[]{x + move[0], y + move[1]});
}
}
}
max = Math.max(max, area);
}
}
return max;
}