[Leetcode] The Maze II

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]];
    }

 

转载于:https://www.cnblogs.com/fifi043/p/6533845.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值