题目
题目描述:
有9只盘子,排成1个圆圈。 其中8只盘子内装着8只蚱蜢,有一个是空盘。 我们把这些蚱蜢顺时针编号为 1~8 每只蚱蜢都可以跳到相邻的空盘中,也可以再用点力,越过一个相邻的蚱蜢跳到空盘中。 请你计算一下,如果要使得蚱蜢们的队形改为按照逆时针排列, 并且保持空盘的位置不变(也就是1-8换位,2-7换位,…),至少要经过多少次跳跃?
输入:
输出:
样例输入
样例输出
无
思路
以空盘子进行广搜,得到的结果为答案
代码
package text;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Set;
import java.util.TreeSet;
public class Main {
public static class loc {
int x;
int step;
int pos[] = new int[9];
loc(){
}
}
static int forward[] = { -2, -1 ,1 ,2};
public static void main(String[] args) {
Set<String> vis = new TreeSet();
loc zero =new loc();
zero.x = 8;
zero.step = 0;
for(int i=0;i<9;i++) {
zero.pos[i]=i;
}
String w=new String();
for(int j=0;j<9;j++) {
w+=Integer.toString(zero.pos[j]);
}
vis.add(w);
Queue<loc> queue =new LinkedList<loc>();
queue.add(zero);
while(!queue.isEmpty()) {
loc s=queue.remove();
// System.out.println(step);
if(s.pos[0]==8&&s.pos[1]==7&&s.pos[2]==6&&s.pos[3]==5&&s.pos[4]==4&&s.pos[5]==3&&s.pos[6]==2&&s.pos[7]==1&&s.pos[8]==0) {
System.out.println(s.step);
return;
}
else {
for(int i=0;i<4;i++) {
int tx=s.x+forward[i];
loc t = new loc();
if(tx<0) {
tx=tx+9;
}
else if(tx>8) {
tx=tx-9;
}
for(int j=0;j<9;j++) {
t.pos[j]=s.pos[j];
}
int temp=t.pos[tx];
t.pos[tx]=t.pos[s.x];
t.pos[s.x]=temp;
String str="";
for(int j=0;j<9;j++) {
str+=Integer.toString(t.pos[j]);
}
if(!vis.contains(str)) {
t.step=s.step+1;
t.x=tx;
// System.out.println(str);
queue.add(t);
vis.add(str);
}
}
}
}
}
}