Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

补充了 0099.岛屿的数量广搜.md 中原有java代码中缺少的pair类的定义;提供了另一种不使用pair,而是使用两个队列分别存储横纵坐标的方案 #2912

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
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
@@ -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;//逻辑同上
}
}