8.抓住那头牛

【题目】


农夫John和一头逃跑的牛在同一坐标轴上,John的初始位置为N(0<N<=100,000),牛的位置为K(0<K<=100,000),假定John在追逐过程中,牛不会移动,John有两种追逐方式:

1)从位置X移动X-1或者X+1需要一分钟时间;

2)一分钟内,可以从位置X移动到位置2*X。

问,John最少需要多少时间追到牛。


输入:
3 8
输出:
2
【思路】

广度优先搜索,用一个队列保存农夫每一步能走到的位置,用一个数组visited保存当前位置是否已经能够提前达到,如果能提前达到则不再走,每次搜索,step+1,如果农夫位置和牛位置重合,就返回step数。

 

【代码】

public static int coupons(int n, int k) {
        int step = 0;
        int[] visited = new int[100001];
        visited[n] = 1;
        Queue<Integer> queue = new LinkedList<>();
        queue.add(n);
        while (queue.size() > 0) {
            int size = queue.size();
            for (int i = size; i >0; i--) {
                int x = queue.poll();
                visited[x] = 1;
                if (x == k) {
                    return step;
                }
                if (visited[x - 1] == 0) {
                    queue.add(x - 1);
                }
                if (visited[x + 1] == 0) {
                    queue.add(x + 1);
                }
                if (x + x > 100000) continue;
                if (visited[x + x] == 0) {
                    queue.add(x + x);
                }
            }
        }
        step++;
        return step;
    }

 

posted @ 2023-08-04 14:05  梦想是能睡八小时的猪  阅读(42)  评论(0)    收藏  举报