题目描述
X 星球的流行宠物是青蛙,一般有两种颜色:白色和黑色。
X 星球的居民喜欢把它们放在一排茶杯里,这样可以观察它们跳来跳去。
如下图,有一排杯子,左边的一个是空着的,右边的杯子,每个里边有一只青蛙。
∗WWWBBB
其中,W 字母表示白色青蛙,B 表示黑色青蛙,∗∗ 表示空杯子。
X 星的青蛙很有些癖好,它们只做 3 个动作之一:
跳到相邻的空杯子里。
隔着 1 只其它的青蛙(随便什么颜色)跳到空杯子里。
隔着 2 只其它的青蛙(随便什么颜色)跳到空杯子里。
对于上图的局面,只要 1 步,就可跳成下图局面:
WWW∗BBB
本题的任务就是已知初始局面,询问至少需要几步,才能跳成另一个目标局面。
输入描述
输入为 2 行,2 个串,表示初始局面和目标局面。我们约定,输入的串的长度不超过 15。
输出描述
输出要求为一个整数,表示至少需要多少步的青蛙跳。
输入输出样例
示例
输入
*WWBB
WWBB*
输出
2
运行限制
最大运行时间:1s
最大运行内存: 256M
代码:
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class 青蛙跳杯子 {
static int[] dir = { -3, -2, -1, 1, 2, 3 };
static int index;
static int step = 0;
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String start = scanner.nextLine();
String end = scanner.nextLine();
bfs(start, end);
System.out.println(step);
}
private static void bfs(String start, String end) {
HashSet<String> set = new HashSet<>();
Queue<String> queue = new LinkedList<>();
set.add(start);
queue.offer(start);
while (!queue.isEmpty()) {
int len = queue.size();
for (int i = 0; i < len; i++) {
String temp = queue.poll();
if (temp.equals(end)) {
return;
}
//获取杯子下标
index = temp.indexOf('*');
//模拟左右跳动
for (int j = 0; j < 6; j++) {
//获取当前位置下标
int tIndex = index + dir[j];
//判断是否越界
if (tIndex >= 0 && tIndex < temp.length()) {
char[] tempChar = temp.toCharArray();
//交换
tempChar[index] = temp.charAt(tIndex);
tempChar[tIndex] = temp.charAt(index);
String s = new String(tempChar);
//判断该场景是否已经存在
if (!set.contains(s)) {
set.add(s);
queue.offer(s);
}
}
}
}
//退出for循环步数就加 1
step++;
}
}
}