Facebook
From Thundering Mousedeer, 3 Years ago, written in Plain Text.
This paste is a reply to Re: Untitled from Speedy Pintail - view diff
Embed
Download Paste or View Raw
Hits: 64
  1. class Solution {
  2.     public int shortestDistance(int[][] maze, int[] start, int[] destination) {
  3.         int nr = maze.length;
  4.         int nc = maze[0].length;
  5.         int[][] distances = new int[nr][nc];
  6.         for (int[] row : distances) {
  7.             Arrays.fill(row, Integer.MAX_VALUE);
  8.         }
  9.         int[][] dirs = {{0, 1}, {0, -1}, {1, 0}, {-1, 0}};
  10.         Queue<int[]> queue = new LinkedList<>();
  11.         queue.add(start);
  12.         while (!queue.isEmpty()) {
  13.             int[] curr = queue.poll();
  14.             for (int[] dir : dirs) {
  15.                 int x = curr[0] + dir[0];
  16.                 int y = curr[1] + dir[1];
  17.                 int count = 0;
  18.                 while (x >= 0 && x < nr &&
  19.                       y >= 0 && y < nc &&
  20.                       maze[x][y] != 1) {
  21.                     x += dir[0];
  22.                     y += dir[1];
  23.                     count++;
  24.                 }
  25.                 if (distances[curr[0]][curr[1]] + count < distances[x-dir[0]][y-dir[1]]) {
  26.                     distances[x-dir[0]][y-dir[1]] = distances[curr[0]][curr[1]] + count;
  27.                     queue.add(new int[]{x - dir[0], y - dir[1]});
  28.                 }
  29.             }
  30.         }
  31.         return distances[destination[0]][destination[1]] == Integer.MAX_VALUE ? -1 : distances[destination[0]][destination[1]];
  32.     }
  33. }