完美世界兔子跳桩问题

做为一个正准备找工作的大四党,刚刚开始投递,看见这样的算法,只能说:唉

当时暴力写,通过率很低,后来复习了图的相关算法。从DFS到BFS到Floyd到迪杰斯特拉算法。。。

总算对这道题解有了思路。

我的解法是BSF,因为牛客上没有原题哈,这里是用的本地ide,也没有按ACM模式的标准来写,

代码:

/**
 * @author YangGuo
 * @version 1.0
 * @date 2021/9/23 9:52
 */
public class BfsInstance {
    private static int[] array;
    private static int[] visited;
    private static Map<String,List<Integer>> path=new HashMap<>();
    private static LinkedBlockingQueue<node> queue = new LinkedBlockingQueue<>();
    public static int gotoEnd(int[] array,int start,int end){
         visited = new int[array.length];
         BfsInstance.array=array;
         queue.offer(new node(start,0));
         visited[start]=1;
        while (!queue.isEmpty()){
            final node poll = queue.poll();
            final int n = poll.start;
            final int step1 = poll.step;
            if(n==end){
                System.out.println(path.get(end+""));
                return step1;
            }
            if(array[n]+n<=end&&visited[array[n]+n]==0){
                queue.offer(new node(array[n]+n,step1+1));
                savePath(poll,array[n]+n);
                visited[array[n]+n]=1;

            }
            for(int i=n-1;i>=0;i--){
                if(visited[i]==0){
                    queue.offer(new node(i,step1+1));
                    savePath(poll,i);
                    visited[i]=1;
                }
            }

        }
        return -1;
    }

    protected static void savePath(node poll, int n){
        //查询到父节点最近路径
        final List<Integer> integers = path.get(poll.start + "");
        //为空说明到父结点的最近路径不存在(即可直接访问)
        if(integers==null) {
            //记录下父结点与此结点,表示可以直接到达
            final List<Integer> l = new ArrayList<>();
            l.add(poll.start);
            l.add(n);
            path.put(n + "",l);
        }else {
            //获取到父节点的最近路径
            final List<Integer> l = new ArrayList<>();
            for(Integer i:integers){
                l.add(i);
            }
            //将该结点加在父节点最近路径记录之后,成为该结点的最近路径
            l.add(n);
            path.put(n + "",l);
        }
    }

}


class node{
    public int start;
    public int step;
    public node(int start, int step) {
        this.start = start;
        this.step = step;
    }
}


emmm,自己测试了几个,但是不知道是不是能100%,还需要大家指正!

        int[] a={3,2,7,2,9,3,5,4,1,2,1,3,5,2,8};
        int[] b={2, 5, 1, 1, 1, 1,1};
        System.out.println(BfsInstance.gotoEnd(b, 0, b.length-1));



































#完美世界笔试##完美世界##笔经#
全部评论

相关推荐

1 收藏 评论
分享
牛客网
牛客企业服务