I cannot find the reason why my code doesn't work. It keeps saying that there's a infinite recursion error. I'm basically trying to solve a maze recursively.
The start and end of the maze are represented with the characters + and -, respectively. The first line of the maze file will be the number of rows and columns, respectively.As your program moves through the maze the current path should also be marked with the + character. Any path leading to a dead end should be marked with the . character. Here is the maze:
https://drive.google.com/file/d/1l15E0Iqvkp-mnPP_vbTfvx93RXjAJzRo/view?usp=sharing
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.txt");
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));
}
}
}
I tried tinkering with backtracking but I had no luck.