该程序应该以递归方式解决迷宫问题。 readMazeFile将文件的内容读入数组,然后solveMaze函数使用该数组来解决迷宫。但在我的主要功能中没有过去if(maze!= null)似乎没有运行。我包括了摆脱空指针异常。 maze = null吗?我不是这么认为,而是idk。感谢您的帮助。
public class solving {
static char maze[][];
static int startingrow;
static int startingcol;
public static void main(String[] args) throws FileNotFoundException {
readMazeFile("maze0.txt");
if (maze != null) {
System.out.print(maze[1][1]);
if (solveMaze(startingrow, startingcol))
System.out.print("Solved!");
else
System.out.print("There is no solution to this maze.");
}
}
static boolean solveMaze(int row, int col) {
// name each movement to make coding easier to understand with the recursion.
char right = maze[row][col + 1];
char left = maze[row][col - 1];
char up = maze[row - 1][col];
char down = maze[row + 1][col];
char markSpot = 'M';
char unmarkSpot = ' ';
// Base case is at the end of the maze
if (right == 'E' || left == 'E' || up == 'E' || down == 'E') {
return true;
}
// What to do if there is an empty space when it moves
if (right == ' ') {
right = markSpot;
if (solveMaze(row, col + 1)) {
return true;
} else {
right = unmarkSpot;
}
}
if (down == ' ') {
down = markSpot;
if (solveMaze(row + 1, col)) {
return true;
} else {
up = unmarkSpot;
}
}
if (left == ' ') {
left = markSpot;
if (solveMaze(row, col - 1)) {
return true;
} else {
left = unmarkSpot;
}
}
if (up == ' ') {
up = markSpot;
if (solveMaze(row - 1, col)) {
return true;
} else {
up = unmarkSpot;
}
}
return false;
}
static char[][] readMazeFile(String mazeFile) throws FileNotFoundException {
Scanner input = new Scanner(new File(mazeFile));
// Find the height and width
int height = input.nextInt();
int width = input.nextInt();
int finalHeight = (2 * height) + 1;
int finalWidth = (2 * width) + 1;
// Create the array and put data from the file in it
char maze[][] = new char[finalHeight][finalWidth];
input.nextLine();
for (int row = 0; row < finalHeight; row++) {
String fileLine = input.nextLine();
for (int col = 0; col < finalWidth; col++) {
char nextChar = fileLine.charAt(col);
maze[row][col] = nextChar;
}
}
// Find the starting point
for (int r = 0; r < finalHeight; r++) {
for (int c = 0; c < finalWidth; c++) {
if (maze[r][c] == 'S') {
int startingrow = r;
int startingcol = c;
//System.out.print(startingrow);
//System.out.print(startingcol);
}
}
}
return maze;
}
}
答案 0 :(得分:3)
maze
中的readMazeFile
变量会影响您在条件中使用的静态变量。
或者:
readMazeFile
。maze
变量(删除readMazeFile
类型声明符)。然后回来就没必要了。答案 1 :(得分:0)
您必须将函数调用的结果存储在main变量迷宫的第一行。由于你没有这样做,迷宫当然是空的。