模板题目:BFS (695. Max Area of Island)
这道题可以说是很经典了。
对每一个点进行bfs 注意对遍历过的点的值的修改 用于防止多次重复统计。而且我们不用像backtracking一样最后再改回来,因为如果两个land联通 那么这两者的面积是一样的。
但是实际上 下面的代码不是BFS 而是典型的DFS因为有递归
class Solution {
private int count = 0;
public int maxAreaOfIsland(int[][] grid) {
if(grid == null || grid.length == 0) return 0;
int res = 0;
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){
helper(grid, i, j); //helper indicates the area expand from (i,j): int
res = Math.max(res, count);// and I believe the mainly mistake here is pass by value and pass by reference, in other words, temp is not changed at all
count = 0;
}
}
}
return res;
}
private void helper(int[][] grid, int i, int j){
if(grid[i][j] == 1){
grid[i][j] = 0;
count++;
if(i>0 && grid[i-1][j] == 1){ //only goes one way or maybe more way will decide whether to use if/if/if or if/else if/else if
helper(grid, i - 1, j);
}
if(i<grid.length - 1 && grid[i+1][j] == 1){
helper(grid, i + 1, j);
}
if(j>0 && grid[i][j-1] == 1){
helper(grid, i, j - 1);
}
if(j<grid[0].length - 1 && grid[i][j+1] == 1){
helper(grid, i, j + 1);
}
return;
}
}
}
真正的BFS代码如下 实际上不太行 这道题实际上是一道典型的DFS题目 但是用强行用BFS也是可以的。
private static int[][] DIRECTIONS = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
// BFS
public int maxAreaOfIsland(int[][] grid) {
if (grid == null || grid.length == 0 || grid[0].length == 0) return 0;
int M = grid.length;
int N = grid[0].length;
boolean[][] visited = new boolean[M][N];
int res = 0;
for (int i=0; i<M; i++) {
for (int j=0; j<N; j++) {
if (grid[i][j] == 1 && !visited[i][j]) {
res = Math.max(res, bfs(grid, visited, i, j));
}
}
}
return res;
}
private int bfs(int[][] grid, boolean[][] visited, int i, int j) {
Queue<int[]> q = new LinkedList<>();
q.add(new int[]{i, j});
visited[i][j] = true;
int res = 0;
while (!q.isEmpty()) {
int[] curr = q.poll();
res++;
for (int[] dir: DIRECTIONS) {
int x = curr[0] + dir[0];
int y = curr[1] + dir[1];
if (x < 0 || y < 0 || x >= grid.length || y >= grid[0].length || visited[x][y] || grid[x][y] != 1) continue;
q.add(new int[]{x, y});
visited[x][y] = true;
}
}
return res;
}
简直就是脱了裤子放屁。

浙公网安备 33010602011771号