Advertisement
Guest User

Grokking 197

a guest
Nov 13th, 2021
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. class Solution {
  2.  
  3.   int[][] DIRS = new int[][] { {-1, 0}, {-1, 1}, {0, 1}, {1, 1}, {1, 0}, {1, -1}, {0, -1}, {-1, -1} };
  4.  
  5.   public int shortestPathBinaryMatrix(int[][] grid) {
  6.     int n = grid.length;
  7.  
  8.     if (grid == null || grid[0][0] != 0 || grid[n - 1][n - 1] != 0) {
  9.       return -1;
  10.     }
  11.  
  12.     Queue<int[]> queue = new LinkedList();
  13.     queue.offer(new int[] {0 , 0});
  14.  
  15.     grid[0][0] = 1;
  16.  
  17.     while (!queue.isEmpty()) {
  18.       int[] cell = queue.poll();
  19.       int r = cell[0];
  20.       int c = cell[1];
  21.  
  22.       int distance = grid[r][c];
  23.  
  24.       // if met destination, return distance
  25.       if (r == n - 1 && c == n - 1) {
  26.         return distance;
  27.       }
  28.  
  29.       // explore all neighbor rows and update new distance
  30.       for (int i = 0; i < 8; i++) {
  31.         int[] dir = DIRS[i];
  32.  
  33.         int rr = r + dir[0];
  34.         int cc = c + dir[1];
  35.  
  36.         if (0 <= rr && rr < n && 0 <= cc && cc < n && grid[rr][cc] == 0) {
  37.           grid[rr][cc] = distance + 1;
  38.  
  39.           queue.offer(new int[] {rr, cc});
  40.         }
  41.       }
  42.     }
  43.  
  44.     return -1;
  45.   }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement