MazeSolver class

mail@pastecode.io avatar
unknown
java
a month ago
2.6 kB
44
Indexable
Never
import java.util.Scanner;

public class MazeSolver {
    private Scanner mazesc;
    private String filename;
    private boolean pathExist = false;
    private Position posStart;
    private Position posEnd;
    private int[][] maze;

    public MazeSolver(String filename, int startCol, int startRow, int endCol, int endRow){
        this.filename = filename;

        try{
            this.mazesc = new Scanner(MazeSolver.class.getResourceAsStream(this.filename));
            int m = mazesc.nextInt();
            int n = mazesc.nextInt();
            this.maze = new int[m][n];
            for(int i = 0;i<m;i++){
                for(int j = 0;j<n;j++){
                    maze[i][j] = mazesc.nextInt();
                }
            }
        } catch (NullPointerException e){
            System.out.println("Input file doesn't exist");
        }

        this.posStart = new Position(startRow, startCol);
        this.posEnd = new Position(endRow, endCol);
    }

    public boolean isValidPosition(int row, int col){
        if(row < 0 || row >= this.maze.length || col < 0 || col >= this.maze[0].length || this.maze[row][col] == 1){
            return false;
        } else return true;
    }

    public void findPath(int row, int col) {
        if(!isValidPosition(row, col)){
            return; // invalid position
        }
        else if(this.maze[row][col] == 2){
            return; // already visited
        }
        else if(row == this.posEnd.getRow() && col == this.posEnd.getCol()){
            pathExist = true;
            this.maze[row][col] = 2;
            printMaze();
        } else {
            this.maze[row][col] = 2;
            if(isValidPosition(row+1,col)){
                findPath(row + 1, col);
            }
            if(isValidPosition(row-1,col)){
                findPath(row - 1, col);
            }
            if(isValidPosition(row, col+1)){
                findPath(row, col + 1);
            }
            if(isValidPosition(row, col-1)){
                findPath(row, col - 1);
            }
            this.maze[row][col] = 0; // backtrack
        }
    }

    public void solve(){
        findPath(posStart.getRow(), posStart.getCol());
        if(!pathExist){
            System.out.println("No path exists from start to end");
        }
    }
    public void printMaze(){
        try {
            for(int i = 0;i < this.maze.length;i++){
                for(int j = 0;j<this.maze[i].length;j++){
                    System.out.print(this.maze[i][j] + " ");
                }
                System.out.println();
            }
        }catch (NullPointerException e){}

    }
}
Leave a Comment