Facebook
From Crippled Wigeon, 2 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 47
  1. class Solution {
  2.     public boolean hasPath(int[][] maze, int[] start, int[] destination) {
  3.         int nr = maze.length;
  4.         int nc = maze[0].length;
  5.         boolean[][] visited = new boolean[nr][nc];
  6.         int[][] dirs = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}};
  7.         Queue<int[]> queue = new LinkedList<>();
  8.         queue.add(start);
  9.         visited[start[0]][start[1]] = true;
  10.         while (!queue.isEmpty()) {
  11.             int[] idx = queue.poll();
  12.             if (idx[0] == destination[0] && idx[1] == destination[1]) {
  13.                 return true;
  14.             }
  15.             for (int[] dir : dirs) {
  16.                 int x = idx[0] + dir[0];
  17.                 int y = idx[1] + dir[1];
  18.                 while (x >= 0 && y >= 0 && x < nr && y < nc &&
  19.                       maze[x][y] == 0) {
  20.                     x += dir[0];
  21.                     y += dir[1];
  22.                 }
  23.                 if (!visited[x - dir[0]][y - dir[1]]) {
  24.                     queue.add(new int[] {x - dir[0], y - dir[1]});
  25.                     visited[x - dir[0]][y - dir[1]] = true;
  26.                 }
  27.             }
  28.         }
  29.         return false;
  30.     }
  31. }

Replies to Untitled rss

Title Name Language When
Re: Untitled Speedy Pintail text 2 Years ago.