慕标5832272
您的问题是path永远不会重置,只会添加。您需要以某种方式跟踪 aPos或关卡的先前位置。尝试这个: while (!q.isEmpty()) { // Pop front node and process Node node = q.poll(); currX = node.x; currY = node.y; int d = node.d; path.removeRange(d, path.size()); path.add(new Pos(curX, curY)); // If end is found, stop if (currX == endX && currY == endY) { min_d = d; break; } // check all 4 directions from curr cell for (int k = 0; k < 4; k++) { if (isValid(maze, visited, currX + r[k], currY + c[k])) { // mark as visited and add to path visited[currX + r[k]][currY + c[k]] = true; q.add(new Node(currX + r[k], currY + c[k], d + 1)); } } }更新:class Node { int x; int y; Node prev; Node(int x, int y, Node prev) { this.x = x; this.y = y; this.prev = prev; }};... while (!q.isEmpty()) { // Pop front node and process Node node = q.poll(); currX = node.x; currY = node.y; // If end is found, stop if (currX == endX && currY == endY) { ArrayList<Pos> path = new ArrayList<>(); do { path.add(0, new Pos(node.x,node.y)); node = node.prev; } while (node != null); return path; } // check all 4 directions from curr cell for (int k = 0; k < 4; k++) { if (isValid(maze, visited, currX + r[k], currY + c[k])) { // mark as visited and add to path visited[currX + r[k]][currY + c[k]] = true; q.add(new Node(currX + r[k], currY + c[k], node)); } } } return null;