Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions problems/kamacoder/0099.岛屿的数量广搜.md
Original file line number Diff line number Diff line change
Expand Up @@ -195,24 +195,27 @@ import java.util.*;

public class Main {
public static int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};//下右上左逆时针遍历

public static void bfs(int[][] grid, boolean[][] visited, int x, int y) {
Queue<pair> queue = new LinkedList<pair>();//定义坐标队列,没有现成的pair类,在下面自定义了
queue.add(new pair(x, y));
Queue<Integer> queueX = new LinkedList<Integer>();//定义两个队列分别存储横纵坐标
Queue<Integer> queueY = new LinkedList<Integer>();
queueX.add(x);
queueY.add(y);
visited[x][y] = true;//遇到入队直接标记为优先,
// 否则出队时才标记的话会导致重复访问,比如下方节点会在右下顺序的时候被第二次访问入队
while (!queue.isEmpty()) {
int curX = queue.peek().first;
int curY = queue.poll().second;//当前横纵坐标
while (!queueX.isEmpty()) {
int curX = queueX.poll();
int curY = queueY.poll();//当前横纵坐标,并拿出队列
for (int i = 0; i < 4; i++) {
//顺时针遍历新节点next,下面记录坐标
//依次遍历新节点next,下面记录坐标
int nextX = curX + dir[i][0];
int nextY = curY + dir[i][1];
if (nextX < 0 || nextX >= grid.length || nextY < 0 || nextY >= grid[0].length) {
continue;
}//去除越界部分
if (!visited[nextX][nextY] && grid[nextX][nextY] == 1) {
queue.add(new pair(nextX, nextY));
queueX.add(nextX);
queueY.add(nextY);
visited[nextX][nextY] = true;//逻辑同上
}
}
Expand Down