Advertisement
amitsen01ei

BackTrackingAssignment

Oct 9th, 2023
46
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.92 KB | Source Code | 0 0
  1. public class RatInAMaze {
  2.  
  3.     private static final int[] dx = {0, 1, 0, -1};
  4.     private static final int[] dy = {1, 0, -1, 0};
  5.  
  6.     private static boolean isSafeToTravel(int[][] m, int x, int y, int n, boolean[][] visited) {
  7.         return x >= 0 && y >= 0
  8.                 && x < n && y < n
  9.                 && m[x][y] == 1 && !visited[x][y];
  10.     }
  11.  
  12.     /**
  13.      * Finds if there's a path from the source (0,0) to the destination (N-1,N-1).
  14.      * Time complexity: O(N^2) in the worst case.
  15.      * Space complexity: O(N^2) due to the visited matrix.
  16.      *
  17.      * @param maze The maze represented as a matrix.
  18.      * @param x The present x co-ordinate
  19.      * @param y The present y co-ordinate
  20.      * @param n The size of the matrix.
  21.      * @param visited A matrix indicating the cells that have been visited.
  22.      * @return true if a path exists, false otherwise.
  23.      */
  24.     private static boolean traverse(int[][] maze, int x, int y, int n, boolean[][] visited) {
  25.         if (x == n - 1 && y == n - 1) {
  26.             return true;
  27.         }
  28.  
  29.         visited[x][y] = true;
  30.  
  31.         for (var i = 0; i < 4; i++) {
  32.             int newX = x + dx[i];
  33.             int newY = y + dy[i];
  34.  
  35.             if (isSafeToTravel(maze, newX, newY, n, visited)) {
  36.                 if (traverse(maze, newX, newY, n, visited)) {
  37.                     return true;
  38.                 }
  39.             }
  40.         }
  41.  
  42.         visited[x][y] = false;
  43.         return false;
  44.     }
  45.  
  46.     /**
  47.      * The public caller function to check if a path exists
  48.      * @param matrix The matrix needed to be traversed
  49.      * @param n The size of the n x n matrix
  50.      * @return true if a path exists, otherwise false
  51.      */
  52.     public static boolean hasPath(int[][] matrix, int n) {
  53.         var visited = new boolean[n][n];
  54.  
  55.         if (matrix[0][0] == 0) {
  56.             return false;
  57.         }
  58.  
  59.         return traverse(matrix, 0, 0, n, visited);
  60.     }
  61. }
  62.  
  63.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement