标题题目描述
如图所示: 有9只盘子,排成1个圆圈。其中8只盘子内装着8只蚱蜢,有一个是空盘。
我们把这些蚱蜢顺时针编号为 1~8。每只蚱蜢都可以跳到相邻的空盘中,也可以再用点力,越过一个相邻的蚱蜢跳到空盘中。
请你计算一下,如果要使得蚱蜢们的队形改为按照逆时针排列,并且保持空盘的位置不变(也就是1-8换位,2-7换位,…),至少要经过多少次跳跃?
标题输出
输出一个整数表示答案
这个题目一开始用dfs写的,但是能力有限写不出,小白在此求dfs版本。
import java.util.*;
import java.util.Queue;
public class Main {
public static Set<Integer> GG = new LinkedHashSet<Integer>(); //set去重
public static int num[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; //我们把数值为9表示空盆
public static int next[] = { -1, 1, 2, -2 }; //交换的4个状态 相邻和次相邻
public static void swap(int x, int y) { // 交换
int temp;
temp = num[x];
num[x] = num[y];
num[y] = temp;
}
public static int Tnum() { //将蚱蜢状态转数字
int ans = 0;
for (int i = 0; i < 9; i++) {
ans = ans * 10 + num[i];
}
return ans;
}
public static void bfs() {
Queue<Node> MM = new LinkedList<Node>(); //创建队列
Node ST = new Node();
ST.num = 123456789;
ST.step = 0;
GG.add(ST.num);
MM.add(ST); //一开始队列加入蚱蜢状态为123456789的 也就是
//起始状态
while (!MM.isEmpty()) {
Node first = MM.poll();
int P = 0;
int NUM = first.num;
for (int i = 8; i >= 0; i--) { //数字转对应的位置 并找出空盆的位置
if (NUM % 10 == 9)
P = i;
num[i] = NUM % 10;
NUM /= 10;
}
for (int i = 0; i < 4; i++) {
swap(P, (P + next[i] + 9) % 9); //空盆位置与相邻,次相邻的位置交换
Node second = new Node();
second.num = Tnum();
second.step = first.step + 1;
if (second.num == 876543219) { //如果交换后的位置转数字满足876543219 输出结果 并且跳出
System.out.println(second.step);
return;
}
if (!GG.contains(second.num)) { //如果该数字不存在 表示队列中没有这个状态 就要加入
GG.add(second.num);
MM.add(second);
}
swap(P, (P + next[i] + 9) % 9);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
bfs();
}
}
class Node {
public int num;
public int step;
}
最后答案为 20