C - Catch That Cow POJ - 3278 JAVA

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;

public class Main
{
	public static int x = 0;

	public static void main(String args[])
	{
		Scanner sc = new Scanner(System.in);
		while (sc.hasNext())
		{
			x = Integer.MAX_VALUE;
			int a, b;
			a = sc.nextInt();
			b = sc.nextInt();
			boolean bool[] = new boolean[1000006];
			if (a >= b)
			{
				System.out.println(a - b);
			} else
			{

				bfs(a, b, 0, bool);

			}

		}
	}

	public static void bfs(int a, int b, int step, boolean[] bool)
	{
		Queue<gg> x = new LinkedList<gg>();
		gg aa = new gg(a, step);
		x.offer(aa);
		while (!x.isEmpty())
		{

			gg g = x.poll();

			if (g.a == b)
			{
				System.out.println(g.step);
				break;
			}
			if (g.a+1>=0 && g.a+1<=100000 && bool[g.a+1]==false)
			{
				gg cnm=new gg(g.a+1,  g.step+1);bool[g.a+1]=true;x.add(cnm);
			}
			if (g.a-1>=0 && g.a-1<100000 && bool[g.a-1]==false ) 
			{
				gg cnm=new gg(g.a-1,  g.step+1);bool[g.a-1]=true;x.add(cnm);
			}
			if (g.a*2>=0 && g.a*2<=100000 && bool[g.a*2]==false)
			{
				gg cnm=new gg(g.a*2, g.step+1);bool[g.a*2]=true;x.add(cnm);
			}
	
		}
	}
}

class gg
{
	int a;
	int step;

	public gg(int a, int step)
	{
		this.a = a;
		this.step = step;
	}
}

你可能感兴趣的:(dfs,bfs)