我找不到我的代码不起作用的原因。它一直在说存在无限的递归错误。我基本上是在试图递归解决迷宫。
迷宫的开始和结尾分别用字符 +和 - 表示。迷宫文件的第一行分别是行的数量和列的数量。当您的程序通过迷宫时,当前路径应应 也用 +字符标记。通往的任何路径 死胡同应标有。特点。 这是迷宫:
import java.io.*;
import java.util.*;
public class Main {
public static char[][] maze;
public static int rows, cols, beginR, beginC;
public static boolean solve = false;
public static void main(String[] args) {
boolean load = loadmaze("maze.dat");
if (load == false) {
System.out.println("Failed to load Maze");
return;
}
if (solverMaze(beginR, beginC)) {
System.out.println("Congrats you beat the Maze!");
}
else {
System.out.println("Not found");
}
pMaze();
}
public static boolean loadmaze(String filename) {
File file = new File(filename);
try(Scanner scan = new Scanner(file)) {
rows = scan.nextInt();
cols = scan.nextInt();
scan.nextLine();
maze = new char[rows][cols];
for(int i = 0; i < rows; i++) {
String lines = scan.nextLine();
for(int l = 0; l < cols; l++) {
maze[i][l] = lines.charAt(l);
if(maze[i][l] == '+') {
beginR = i;
beginC = l;
}
}
}
return true;
} catch(FileNotFoundException e) {
System.out.println("Error in loading file");
}
catch(Exception e) {
System.out.println("Error in read maze");
}
return false;
}
private static boolean solverMaze(int row, int column) {
if(row < 0 || column < 0 || row >=rows || column >=cols || maze[row][column] == 'X' || maze[row][column] == '.' || solve){
return false;
}
if(maze[row][column] == '-') {
solve = true;
return true;
}
if(maze[row][column] != '+' ) {
maze[row][column] = '+';
}
if(solverMaze(row + 1, column) || solverMaze(row - 1, column) || solverMaze(row, column + 1) || solverMaze(row, column - 1)) {
return true;
}
maze[row][column] = '.';
return false;
}
private static void pMaze() {
for (char[] row : maze) {
System.out.println(new String(row));
}
}
}
我试图修补回溯,但我没有运气。
static
+
以及使用递归通常都在要求麻烦。
您的一般方法似乎是:将当前的“位置”设置为+
,然后通过向右看,向上,向下和左侧看(这些呼叫)来恢复(如果我们发现它,则会重复出现),如果没有,如果没有,将当前的“位置”设置为'。我们有我们的答案。 this不起作用:看起来“左”的代码毕竟看起来“正确”。 您的工作什么都没做:您不做
:“哦,是a +,所以我不需要重复。”您的代码只是说:如果还不是 +,请加分。这是:
if(maze[row][column] != '+' ) {
maze[row][column] = '+';
}
与:相同
maze[row][column] = '+';
所有之后,该行的值是 +。
您实际上并没有对那个 +做任何东西。然后,您之后将值设置为maze[row][column]
,因此,您可以重复出现,然后再次用点覆盖您的pluss。
因此,您的算法永无止境:您递归地看正确,最终将递归左眼,这将再次递归地向右看,一遍又一遍地看。
如果您想摆脱递归的基本规则(这是共享状态,averything
是通过参数和返回的值携带的),请随时进行实验,但您不会变得非常非常远没有先学习如何调试这样的事情:编写代码,向您显示每个递归步骤,打印网格等等。了解如何使用调试器等踏上来等。