题目描述
你玩过华容道的游戏吗?
这是个类似的,但更简单的游戏。
看下面 3 x 2 的格子
+---+---+---+
| A | * | * |
+---+---+---+
| B | | * |
+---+---+---+
在其中放 5 张牌,其中 A 代表关羽,B 代表张飞,* 代表士兵。
还有个格子是空着的。
你可以把一张牌移动到相邻的空格中去(对角不算相邻)。
游戏的目标是:关羽和张飞交换位置,其它的牌随便在哪里都可以。
输入描述
输入两行 6 个字符表示当前的局面
输出描述
一个整数,表示最少多少步,才能把 A B 换位(其它牌位置随意)
输入输出样例
示例
输入
* A
**B
输出
17
运行限制
最大运行时间:1s
最大运行内存: 256M
代码:
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
import javax.sound.midi.Soundbank;
public class 卡片换位 {
static int[] dir = { -3, -1, 1, 3 };
static int step = 0;// 步数
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String str1 = scanner.nextLine();
String str2 = scanner.nextLine();
// String str = str1 + str2;
String str = str1.concat(str2);
// 获取 A 和 B 的位置
int Aindex = str.indexOf('A');
int Bindex = str.indexOf('B');
bfs(str, Aindex, Bindex);
}
private static void bfs(String str, int Aindex, int Bindex) {
Queue<String> queue = new LinkedList<>();
HashSet<String> set = new HashSet<>();//set用于去重
queue.offer(str);
set.add(str);
while (!queue.isEmpty()) {
int len = queue.size();
while (len-- > 0) {
String temp = queue.poll();
// 出口
if (temp.charAt(Aindex) == 'B' && temp.charAt(Bindex) == 'A') {
System.out.println(step);
return;
}
// 获取空格位置
int index = temp.indexOf(' ');
for (int i = 0; i < 4; i++) {
int newIndex = index + dir[i];
if (newIndex < 0 || newIndex > temp.length() - 1) {
continue;
}
if ((index % 3 == newIndex % 3) || (index / 3 == newIndex / 3)) {
//交换
char[] tempChar = temp.toCharArray();
tempChar[index] = temp.charAt(newIndex);
tempChar[newIndex] = temp.charAt(index);
String s = new String(tempChar);
if (!set.contains(s)) {
set.add(s);
queue.offer(s);
}
}
}
}
step++;
}
}
}