• Source
    1. /* package whatever; // don't place package name! */
    2.  
    3. import java.util.*;
    4. import java.lang.*;
    5. import java.io.*;
    6.  
    7. /**
    8.  * Maze is given as N*N binary matrix of blocks where source block is the upper left most block
    9.  * i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1].
    10.  * A rat starts from source and has to reach destination. The rat can move only in two directions: forward and down.
    11.  *
    12.  * In the maze matrix, 0 means the block is dead end and 1 means the block can be used in the path from source to destination.
    13.  * Note that this is a simple version of the typical Maze problem.
    14.  * For example, a more complex version can be that the rat can move in 4 directions and
    15.  * a more complex version can be with limited number of moves.
    16.  */
    17. class Ideone {
    18. public static void main(String[] args){
    19. int[][] ratMaze = {
    20. {1, 0, 0, 0},
    21. {1, 1, 0, 1},
    22. {0, 1, 0, 0},
    23. {1, 1, 1, 1}
    24. };
    25.  
    26. int[][] solution = new int[ratMaze.length][ratMaze[0].length];
    27. boolean pathExists = isPathExist(ratMaze, solution, 0, 0);
    28. System.out.println("path exists => "+ pathExists);
    29.  
    30. //Print path of rat traversal in maze
    31. for(int i=0; i< solution.length; i++){
    32. for(int j=0; j< solution[0].length; j++){
    33. if(solution[i][j] == 1)
    34. System.out.println("( "+i+ ", "+ j + ")");
    35. }
    36. }
    37. }
    38.  
    39. private static boolean isPathExist(int[][] maze,int[][] solution, int curX, int curY){
    40. if(curX < 0 || curX >= maze.length || curY < 0 || curY >= maze.length){
    41. return false;
    42. }
    43.  
    44. if(curX == maze.length-1 && curY == maze[0].length -1){
    45. solution[curX][curY] = 1;
    46. return true;
    47. }
    48.  
    49. if(maze[curX][curY] == 1){
    50. solution[curX][curY] = 1;
    51. //Traversing either right or downward directions
    52. if(isPathExist(maze, solution, curX +1, curY) || isPathExist(maze, solution, curX, curY + 1)){
    53. return true;
    54. }else{
    55. solution[curX][curY] = 0;
    56. }
    57. }else{
    58. solution[curX][curY] = 0;
    59. }
    60. return false;
    61. }
    62. }
    63.