Search code examples
javarecursionbacktracking

Rat in a maze problem using backtracking in java


I have written the java code but it is not giving any output.Could anyone help me with the solution.thank you.I have provided the input and the output.

Here is the code-

Input- 5 4 OXOO OOOX OOXO XOOO XXOO

Output- 1 0 0 0 1 1 0 0 0 1 0 0 0 1 1 1 0 0 0 1

import java.util.*;

public class ratMaze {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int N = sc.nextInt();
        int M = sc.nextInt();
        char[][] ch = new char[N][M];
        for(int i=0;i<N;i++)
        {
            for(int j=0;j<M;j++)
            {
                ch[i][j]=sc.next().charAt(0);
            }
        }
        int[][] visited = new int[N][M];
        boolean res=ratmaze(ch,0,0,visited);
        if(res)
            print(visited,N,M);
        else
            System.out.print("-1");

    }

    private static boolean ratmaze(char[][]ch,int row,int col,int[][] visited)
    {
        if(row==ch.length-1 && col==ch[0].length-1)
            return true;

        if(row==ch.length || col==ch[0].length || ch[row][col]=='X' || visited[row][col]==1)
            return false;

        visited[row][col]=1;

        //Right
        ratmaze(ch,row,col+1,visited);

        //Down
        ratmaze(ch,row+1,col,visited);

        visited[row][col]=0;

        return true;
    }

    private static void print(int[][] visited,int row,int col)
    {
        for(int i=0;i<row;i++)
        {
            for(int j=0;j<col;j++)
            {
                System.out.print(visited[row][col]+" ");
            }
            System.out.println();
        }
    }

}

Solution

  • There are two issues with your code. First comes from the way you read input characters. Scanner.next() returns a whole token. In this context, a token is a "word" - something limited by whitespaces or start/end of a line. In your example input "OXOO" is one token. You need to modify your your reading in such a way that token is read in the outer loop and then access characters at specific positions. You could do something like this:

    for (int i = 0; i < N; i++) {
        String token = sc.next();
        for (int j = 0; j < M; j++) {
            ch[i][j] = token.charAt(j);
        }
    }
    

    It "worked" the way you did it but required each character to be separated by whitespace.

    After fixing that you will get an ArrayIndexOutOfBoundsException in print() method. You should use i and j while printing the array, not row and col.

    This will result in some output. I'm not sure if it is the output you expected.