Программа должна рекурсивно решать лабиринт. readMazeFile считывает содержимое файла в массив, тогда функция solveMaze использует этот массив для решения лабиринта. но в моей основной функции ничего не прошло, если (maze! = null), похоже, не работает. Я включил это, чтобы избавиться от исключения нулевого указателя. Лабиринт = нуль? Я так не думал, но ик. Заранее благодарны за Вашу помощь.Почему моя функция не запущена в моей программе (java)?
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;
}
}
Похоже, что это будет для меня недействительным. Как вы думаете, почему это не будет ошибкой? – bradimus
'readMazeFile' не может вернуть null (хороший), поэтому нет смысла пытаться выполнить нуль-проверку. Это просто добавляет шум. Но поскольку вы все равно не сохраняете возвращаемое значение, вы просто проверяете затененный «лабиринт», который никогда не создается. –