目录
题目描述
如下图的九宫格中,放着 1 ~ 8 的数字卡片,还有一个格子空着。与空格子相邻的格子中的卡片可以移动到空格中。 经过若干次移动,可以形成图 2 所示的局面。
我们把上图的局面记为:12345678.
把下图的局面记为:123.46758
显然是按从上到下,从左到右的顺序记录数字,空格记为句点。
题目的任务是已知九宫的初态和终态,求最少经过多少步的移动可以到达。如果无论多少步都无法到达,则输出 -1。
输入描述
输入第一行包含九宫的初态,第二行包含九宫的终态。
输出描述
输出最少的步数,如果不存在方案,则输出 -1。
输入输出样例
示例
输入
12345678.
123.46758
输出
3
运行限制
- 最大运行时间:2s
- 最大运行内存: 256M
原题链接
九宫重排https://www.lanqiao.cn/problems/261/learning/
代码思路
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static int[][] wz = { { 1, 3 }, { 0, 4, 2 }, { 1, 5 }, { 0, 4, 6 }, { 1, 3, 5, 7 }, { 2, 4, 8 }, { 3, 7 },
{ 6, 4, 8 }, { 5, 7 } };
static String start;
static String end;
static HashMap<String, Integer> map = new HashMap<String, Integer>();
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
start = scanner.next();
end = scanner.next();
bfs();
}
static void bfs() {
Queue<String> queue = new LinkedList<String>();
queue.add(start);
map.put(start, 0);
while (!queue.isEmpty()) {
String temp = queue.poll();
if (temp.equals(end)) {
System.out.println(map.get(temp));
return;
}
int position = temp.indexOf(".");
for (int i = 0; i < wz[position].length; i++) {
StringBuilder sb = new StringBuilder(temp);
sb.setCharAt(position, sb.charAt(wz[position][i]));
sb.setCharAt(wz[position][i], '.');
String string = sb.toString();
if (!map.containsKey(string)) {
queue.add(string);
map.put(string, map.get(temp) + 1);
}
}
}
System.out.println(-1);
}
}