运用bfs算法
蒜头君不能移动到坐标小于0或大于n的位置。蒜头想知道从A点移动到B点的最少步数是多少,你能帮他计算出来么?
第一行输入三个整数n,A,B,分别代表坐标轴长度,起始点坐标,终点坐标。(0≤A,B≤n≤50000)
输出一个整数占一行,代表蒜头要走的最少步数。
样例输入
10 2 7
样例输出
3
import java.util.*; class Yidong{ int step = 0,x=0; public Yidong(){ } public Yidong(int x,int step){ this.x=x; this.step = step; } } public class Main { static int n=0,A=0,B=0,result=0; static int[] oprate = {1,-1,2}; static int[] visit = null; public static void main(String[] args) { // TODO Auto-generated method stub Scanner sc = new Scanner(System.in); n=sc.nextInt(); A=sc.nextInt(); B=sc.nextInt(); visit = new int[n+1]; bfs(A); System.out.print(result); } public static void bfs(int a){ Queue<Yidong> queue = new LinkedList<Yidong>(); visit[a] = 1; queue.offer(new Yidong(a,0)); int flag = Math.abs(A-B); while(!queue.isEmpty()){ Yidong temp = queue.poll(); boolean find = false; for(int i=0;i<3;i++){ if(i==2){ if(temp.x*2<=n){ if(temp.x*2==B){ result = temp.step+1; find = true; break; } if(visit[temp.x*2]==0){ visit[temp.x*2]=1; queue.offer(new Yidong(temp.x*2,temp.step+1)); } } }else{ if(temp.x+oprate[i]<=n){ if(temp.x+oprate[i] == B){ result = temp.step+1; find = true; break; } if(visit[temp.x+oprate[i]]==0){ visit[temp.x+oprate[i]]=1; queue.offer(new Yidong(temp.x+oprate[i],temp.step+1)); } } } } if(find){ break; } } } }