import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
class points {
int x, y;
public points(int x, int y) {
this.x = x;
this.y = y;
}
}
public class Main {
static int b,n,min;
static Queue<points> q = new LinkedList<points>();
static int[] vis = new int[5001];
static void bfs(int x,int y){
vis[x]=1;
q.add(new points(x,y));
while(!q.isEmpty()){
points p = q.poll();
if(p.x<0 || p.x>n)
return;
if(p.x==b)
min= p.y;
if(p.x+1>=0 && p.x+1<=n && vis[p.x+1]==0)
{
vis[p.x+1]=1;
q.add(new points(p.x+1,p.y+1));
}
if(p.x-1>=0 && p.x-1<=n && vis[p.x-1]==0)
{
vis[p.x-1]=1;
q.add(new points(p.x-1,p.y+1));
}
if(p.x*2>=0 && p.x*2<=n && vis[2*p.x]==0)
{
vis[p.x*2]=1;
q.add(new points(p.x*2,p.y+1));
}
}
}
//dfs超栈
/* static void dfs(int i,int sum){
if(sum>n || sum<0)
return;
if(b==sum){
min=Math.min(min, i);
return;
}
if(sum+1>=0 && sum+1<=n)
dfs(i+1,sum+1);
if(sum-1>=0 && sum-1<=n)
dfs(i+1,sum-1);
if(sum*2>=0 && sum*2<=n)
dfs(i+1,sum*2);
}*/
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
n = sc.nextInt();
int a = sc.nextInt();
b = sc.nextInt();
bfs(a,0);
System.out.println(min);
}
}
一维数组的移动
最新推荐文章于 2023-04-11 13:32:40 发布