在一个长度为n的一维坐标轴中,蒜头君想从A点移动到B点,移动规则如下:
1,向前一步,坐标增加1
2,向后一步,坐标减少1
3,跳跃一步,坐标乘2
蒜头君不能移动到坐标小于0或大于n的位置,求从A到B的最小步数。
求最短,bfs。
代码如下:
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class L3 {
static int n, A, B;
static boolean[] vis = new boolean[110];
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();
int now, step = 0;
Queue<Pair> q = new LinkedList<>();
q.offer(new Pair(A, 0));
vis[A] = true;
while (!q.isEmpty()) {
now = q.peek().pos;
step = q.peek().step;
q.poll();
if (now == B) {
System.out.println(step);
break;
}
if (now + 1 <= n && !vis[now + 1]) {
q.offer(new Pair(now + 1, step + 1));
vis[now + 1] = true;
}
if (now - 1 >= 0 && !vis[now - 1]) {
q.offer(new Pair(now - 1, step + 1));
vis[now - 1] = true;
}
if (now * 2 <= n && !vis[now * 2]) {
q.offer(new Pair(now * 2, step + 1));
vis[now * 2] = true;
}
}
}
}
class Pair {
int pos, step;
public Pair(int pos, int step) {
this.pos = pos;
this.step = step;
}
}