poj3278 Catch That Cow |bfs|队列|Java

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_31650113/article/details/79645813

http://poj.org/problem?id=3278

import java.sql.Time;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main{

    public static int k, n;
    public static int MAXN = 100000;
    public static int[] vis = new int[100005];

    public static class P {
        int p;
        int time;

        P(int x, int y) {
            p = x;
            time = y;
        }
    }

    public static void bfs() {
        return;
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNext()) {
            Arrays.fill(vis, 0);

            n = scanner.nextInt();
            k = scanner.nextInt();

            P p = new P(n, 0);
            Queue<P> q = new LinkedList<P>();
            q.offer(p);
            vis[n] = 1;
            while (!q.isEmpty()) {
                P t = q.poll();
                if (t.p == k) {
                    System.out.println(t.time);
                    break;
                } else {
                    if (t.p - 1 >= 0 && vis[t.p - 1] != 1) {
                        q.offer(new P(t.p - 1, t.time + 1));
                        vis[t.p - 1] = 1;
                    }
                    if (t.p + 1 <= MAXN && vis[t.p + 1] != 1) {
                        q.offer(new P(t.p + 1, t.time + 1));
                        vis[t.p + 1] = 1;
                    }
                    if (t.p * 2 <= MAXN && vis[t.p*2] != 1) {
                        q.offer(new P(t.p * 2, t.time + 1));
                        vis[t.p * 2] = 1;
                    }
                    //System.out.print(t.p*2+"=");
                    //System.out.println(t.time);
                }
            }
        }
        return;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_31650113/article/details/79645813
今日推荐