https://leetcode.com/problems/the-maze-ii/?tab=Description
Thought:
- BFS:
It's looking for shortest distance, the initial thought is that BFS could be better than DFS.
- The only difference from The Maze is that it needs a length[][] to store shortest length to current point. Unlike part one, which we only care whether this point has been through already(If yes, we simply skip), here we can't skip going to the same point gain, it is possible that different routes have a common point. We update distance each time to make sure it saves the shortest distance.
- If current distance is greater that current distance to destination, then we shouldn't even keep going.
public int shortestDistance(int[][] maze, int[] start, int[] destination) { if(maze == null || maze.length==0){ return -1; } Queue<List<Integer>> points = new LinkedList<List<Integer>>(); points.offer(Arrays.asList(start[0],start[1],0)); int[][] visited = new int[maze.length][maze[0].length]; for(int i=0;i<visited.length;i++){ Arrays.fill(visited[i], Integer.MAX_VALUE); } visited[start[0]][start[1]] = 0; int[] offsets = new int[]{0,1,0,-1,0}; while(!points.isEmpty()){ List<Integer> cur = points.poll(); for(int i=0;i<offsets.length-1;i++){ int x = cur.get(0); int y = cur.get(1); int dis = cur.get(2); while((x + offsets[i]>=0&&x+offsets[i]<maze.length) && (y+offsets[i+1]>=0 && y+offsets[i+1]<maze[0].length) && maze[x + offsets[i]][y+offsets[i+1]] == 0){ x += offsets[i]; y += offsets[i+1]; dis++; } // if it exceeds distance to current destination, then stop if(dis > visited[destination[0]][destination[1]]) { continue; } if(dis < visited[x][y]){ points.offer(Arrays.asList(x,y,dis)); visited[x][y] = dis; } } } return visited[destination[0]][destination[1]] == Integer.MAX_VALUE ? -1 : visited[destination[0]][destination[1]]; }