思路
- 这个题就是搜索 不管是dfs或者是bfs都可 反正搜索最多相邻的1的个数就好 主要就是熟悉一下模板
- 首先最外层一个循环 遍历所有结点,如果该节点没有被遍历过,那就调用辅助函数
- 还需要学习的是这种迷宫走法 如何快速用代码实现
BFS 用队列~
class Solution {
int max;
int[][] grid;
boolean[][] isVisited;
public int maxAreaOfIsland(int[][] grid) {
max = 0;
this.grid = grid;
isVisited = new boolean[grid.length][grid[0].length];
for(int i = 0 ; i < grid.length ; i++){
for(int j = 0 ; j < grid[0].length ; j++){
if(!isVisited[i][j] && 1 == grid[i][j])
max = Math.max(max , getMaxArea(i,j));
}
}
return max;
}
private int getMaxArea(int i , int j){
int area = 0;
Queue<int[]> queue = new LinkedList<>();
queue.offer(new int[]{i,j});
isVisited[i][j] = true;
int[][] dirs = new int[][]{{-1,0},{0,-1},{1,0},{0,1}};
while(!queue.isEmpty()){
int[] pos = queue.poll();
area++;
for(int[] dir :dirs){
int x = pos[0] + dir[0] , y = pos[1] + dir[1];
if(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && 1 == grid[x][y] && !isVisited[x][y]){
queue.offer(new int[]{x,y});
isVisited[x][y] = true;
}
}
}
return area;
}
}
DFS 把队列改成栈即可~
class Solution {
int max;
int[][] grid;
boolean[][] isVisited;
public int maxAreaOfIsland(int[][] grid) {
max = 0;
this.grid = grid;
isVisited = new boolean[grid.length][grid[0].length];
for(int i = 0 ; i < grid.length ; i++){
for(int j = 0 ; j < grid[0].length ; j++){
if(!isVisited[i][j] && 1 == grid[i][j])
max = Math.max(max , getMaxArea(i,j));
}
}
return max;
}
private int getMaxArea(int i , int j){
int area = 0;
Stack<int[]> stack = new Stack<>();
stack.push(new int[]{i,j});
isVisited[i][j] = true;
int[][] dirs = new int[][]{{-1,0},{0,-1},{1,0},{0,1}};
while(!stack.isEmpty()){
int[] pos = stack.pop();
area++;
for(int[] dir :dirs){
int x = pos[0] + dir[0] , y = pos[1] + dir[1];
if(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && 1 == grid[x][y] && !isVisited[x][y]){
stack.push(new int[]{x,y});
isVisited[x][y] = true;
}
}
}
return area;
}
}
递归版本DFS
class Solution {
int max;
int[][] grid;
boolean[][] isVisited;
public int maxAreaOfIsland(int[][] grid) {
max = 0;
this.grid = grid;
isVisited = new boolean[grid.length][grid[0].length];
for(int i = 0 ; i < grid.length ; i++){
for(int j = 0 ; j < grid[0].length ; j++){
if(!isVisited[i][j] && 1 == grid[i][j])
max = Math.max(max , getMaxArea(i,j));
}
}
return max;
}
private int getMaxArea(int i , int j){
int area = 1;
isVisited[i][j] = true;
int[][] dirs = new int[][]{{-1,0},{0,-1},{1,0},{0,1}};
for(int[] dir :dirs){
int x = i + dir[0] , y = j + dir[1];
if(x >= 0 && x < grid.length && y >= 0 && y < grid[0].length && 1 == grid[x][y] && !isVisited[x][y]){
area += getMaxArea(x,y);
}
}
return area;
}
}