路径查找算法陷入无限循环问题求助
网格路径查找GUI的无限循环Bug求助
我正在开发一款网格路径查找GUI,起点固定为(0,0)(海星所在位置),目标点通过Random类依据网格边界随机生成。调试时发现算法陷入无限循环,无法找到路径——海星会反复左右移动,产生大量无效操作。
相关代码如下:
private Queue<Point> findPath(Rectangle[][] matrix, Point destPoint) { Point move = null; var dir = new ArrayList<Point>(); dir.add(new Point(1, 0)); // 右 dir.add(new Point(0, 1)); // 下 dir.add(new Point(-1, 0)); // 左 dir.add(new Point(0, -1)); // 上 Point start = new Point(0, 0); var tmpPath = new ArrayDeque<Point>(); var path = new ArrayDeque<Point>(); tmpPath.add(new Point(0, 0)); while (!tmpPath.isEmpty()) { for (int dc = 0; dc < dir.size(); dc++) { move = new Point(start.x() + dir.get(dc).x(), start.y() + dir.get(dc).y()); if (!move.isValid(matrix[0].length, matrix.length)) { continue; } if (matrix[move.y()][move.x()].getFill() != Color.MAGENTA) { start = move; tmpPath.add(move); path.add(tmpPath.poll()); System.out.println(path.peek()); if (path.getLast().equals(destPoint)) { path.poll(); return path; } break; } } } return null; }
说明:
- 该方法将走过的路径存入队列,到达目标点时返回队列
Color.MAGENTA代表墙体,点击GUI中的矩形会将其颜色设为MAGENTA
我无法解决此bug,请求帮助,项目仓库为maze-solver。
内容的提问来源于stack exchange,提问作者Giorgi Chapidze
相关产品推荐
相关产品推荐

