Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public int shortestDistance(int[][] maze, int[] start, int[] destination)
- {
- // Queue<int[]> q = new PriorityQueue<>((a, b)->(a[2] - b[2]));
- Queue<int[]> q = new LinkedList<>();
- q.offer(new int[]{start[0], start[1], 0});
- int m = maze.length, n = maze[0].length;
- int[][] visited = new int[m][n];
- for(int[] v : visited) Arrays.fill(v, 10001);
- int[] dx = {0, 1, 0, -1}, dy = {1, 0, -1, 0};
- while(!q.isEmpty())
- {
- int[] p = q.poll();
- int i = p[0], j = p[1], step = p[2];
- // if(i == destination[0] && j == destination[1]) return step;
- if(visited[i][j] <= step) continue;
- visited[i][j] = step;
- for(int k = 0; k < 4; k++)
- {
- int ni = i, nj = j;
- while(ni >= 0 && ni < m && nj >= 0 && nj < n && maze[ni][nj] == 0)
- {
- ni += dx[k];
- nj += dy[k];
- }
- ni -= dx[k];
- nj -= dy[k];
- int nstep = step + Math.abs(ni - i) + Math.abs(nj - j);
- q.offer(new int[]{ni, nj, nstep});
- }
- }
- // return -1;
- return visited[destination[0]][destination[1]] == 10001 ? -1 : visited[destination[0]][destination[1]];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement