695. 岛屿的最大面积
问题695 岛屿的最大面积 ★★☆☆☆
https://leetcode-cn.com/problems/max-area-of-island/
BFS的解法并不难理解。从某个点开始,上下左右四个方向,联通的点入队列,同时,为了避免重复,借助一个visited的布尔数组。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
int[] dx = new int[] {0, -1, 0, 1};
int[] dy = new int[] {1, 0, -1, 0};
public int maxAreaOfIsland(int[][] grid) {
int maxArea = 0;
int m = grid.length;
int n = grid[0].length;
Queue<int[]> queue = new LinkedList<>();
boolean[][] visited = new boolean[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (grid[i][j] == 1 && visited[i][j] == false) {
queue.clear();
queue.add(new int[] {i, j});
visited[i][j] = true;
int area = 1;
while (!queue.isEmpty()) {
int[] cur = queue.poll();
for (int k = 0; k < 4; k++) {
int nextRow = cur[0] + dx[k];
int nextCol = cur[1] + dy[k];
if (nextRow >= 0 && nextRow < m
&& nextCol >= 0 && nextCol < n
&& grid[nextRow][nextCol] == 1
&& visited[nextRow][nextCol] == false) {
queue.add(new int[] {nextRow, nextCol});
visited[nextRow][nextCol] = true;
area++;
}
}
}
if (area > maxArea) {
maxArea = area;
}
}
}
}
return maxArea;
}
本文由作者按照 CC BY 4.0 进行授权