[snap]fly drone

instant

主要思路仍然是bfs,利用数据结构存储当前飞行高度。
比较重要的一点是正确剪枝,可以通过比较当前距离d + 当前飞行高度h 与 **目前得到结果 ** 的大小来确定是否需要继续搜索这个分支。

package snapchat;

import java.util.LinkedList;
import java.util.Queue;

/**
 * Created by kangyue on 1/5/17.
 */
public class FlyDrone {

    int res;

    class Con{
        int[] pos;
        int height;
        int dis;

        Con(int i, int j, int h,int d){
            this.pos = new int[]{i,j};
            this.height = h;
            this.dis = d;
        }
    }


    public int shortestDistance(int[][] grid, int[] start, int[] end){

        this.res = Integer.MAX_VALUE;


        Queue q = new LinkedList<>();

        int row = grid.length;
        int col = grid[0].length;

        boolean[][] visit = new boolean[row][col];


        int departHeight = grid[start[0]][start[1]];
        int desHeight = grid[end[0]][end[1]];


        q.offer(new Con(start[0],start[1],grid[start[0]][start[1]],0));


        int[] dx = new int[]{1,-1,0,0};
        int[] dy = new int[]{0,0,1,-1};

        while(!q.isEmpty()){

            Con cur = q.poll();

            int x = cur.pos[0];
            int y = cur.pos[1];

            int h = cur.height;
            int d = cur.dis;

            visit[x][y] = true;

            if(x == end[0] && y == end[1]){
                res = Math.min(res,d + Math.abs(h - desHeight) + Math.abs(h - departHeight));
                continue;
            }

            if(d + Math.abs(h - desHeight) > res)continue;

            for(int c = 0; c < 4; c++){

                int nx = x + dx[c];
                int ny = y + dy[c];

                if(nx >= 0 && nx < row && ny >= 0 && ny < col && !visit[nx][ny]){

                    int nh = grid[nx][ny];

                    q.offer(new Con(nx,ny,Math.max(h,nh),d + 1));

                }
            }

        }

        return res;



    }

    public static void main(String[] args){
        FlyDrone fd = new FlyDrone();
        int[][] tester = new int[][]{{0,0,0,0,0},{0,0,0,0,2},{0,0,0,2,1}};
        System.out.println(fd.shortestDistance(tester,new int[]{0,0},new int[]{2,4}));
    }
}

你可能感兴趣的:([snap]fly drone)