java - BFS 问题返回值始终为空
问题描述
我正在研究这个算法,但无法弄清楚为什么我总是得到一个空返回。代码添加到两个数组 fx 和 fy,它收集 x 和 y 位置,这些位置将以最短路径完成迷宫。问题是没有任何东西被添加到数组中。有什么建议么?
public class Maze {
public List<Integer> fx;
public List<Integer> fy;
public int listSize;
public Point p;
public int[][] cells;
public Maze(int x, int y, int[][] cells) {
p = getPathBFS(x, y, cells);
this.cells = cells;
fx = new ArrayList<>();
fy = new ArrayList<>();
addPoint();
}
private static class Point {
int x;
int y;
Point parent;
public Point(int x, int y, Point parent) {
this.x = x;
this.y = y;
this.parent = parent;
}
public Point getParent() {
return this.parent;
}
}
public static Queue<Point> q = new LinkedList<>();
public Point getPathBFS(int x, int y, int[][] cells) {
q.add(new Point(x, y, null));
while (!q.isEmpty()) {
Point p = q.remove();
if (cells[p.x][p.y] == 9) {
return p;
}
if (isFree(p.x + 1, p.y, cells.length, cells)) {
cells[p.x][p.y] = 2;
Point nextP = new Point(p.x + 1, p.y, p);
q.add(nextP);
}
if (isFree(p.x - 1, p.y, cells.length, cells)) {
cells[p.x][p.y] = 2;
Point nextP = new Point(p.x - 1, p.y, p);
q.add(nextP);
}
if (isFree(p.x, p.y + 1, cells.length, cells)) {
cells[p.x][p.y] = 2;
Point nextP = new Point(p.x, p.y + 1, p);
q.add(nextP);
}
if (isFree(p.x, p.y - 1, cells.length, cells)) {
cells[p.x][p.y] = 2;
Point nextP = new Point(p.x, p.y - 1, p);
q.add(nextP);
}
}
return null;
}
public static boolean isFree(int x, int y, int cellLength, int[][] cells) {
if ((x >= 0 && x < cellLength) && (y >= 0 && y < cells[x].length) && (cells[x][y] == 0 || cells[x][y] == 9)) {
return true;
}
return false;
}
public synchronized void addPoint() {
System.out.println(p);
while ((p != null)) {
System.out.println("x is " + p.x + " - y is " + p.y);
fy.add(p.x);
fx.add(p.y);
p = p.getParent();
}
}
int getListSize() {
listSize = fx.size() - 1;
return listSize;
}
}
解决方案
推荐阅读
- python - 如何使用python获得给定显着性水平的拒绝区域
- excel - 使用 VBA 自动过滤列时如何仅包含特定单词
- c - 检查用户是否根据格式输入
- python - TensorFlow:设计自定义层时 __call__() 和 call() 的功能之间的区别?
- c++ - 为什么函数二返回 cout << s << " " << t << " " << b << endl; 当它说只返回(b)时?
- python - 如何解决 FieldError - 无法将关键字“slug”解析为字段
- mysql - DUPLICATE KEY UPDATE 只能工作一次?
- android - 为什么我的搜索栏没有隐藏提示“搜索...”?
- spring-batch - 如何在spring-batch中将参数从作业传递到FlowStep?
- javascript - 脚本源的动态更改不起作用