题目描述:
如下面第一个图的九宫格中,放着 1~8 的数字卡片,还有一个格子空着。
与空格子相邻的格子中的卡片可以移动到空格中。经过若干次移动,可以形成第二个图所示的局面。
我们把第一个图的局面记为:12345678.
把第二个图的局面记为:123.46758
显然是按从上到下,从左到右的顺序记录数字,空格记为句点。
本题目的任务是已知九宫的初态和终态,求最少经过多少步的移动可以到达。
如果无论多少步都无法到达,则输出-1。
输入:
输入第一行包含九宫的初态,第二行包含九宫的终态。
输出:
输出最少的步数,如果不存在方案,则输出-1。
样例输入:
12345678.
123.46758
样例输出
3
参考解答:
import java.util.Scanner;
import java.util.Deque;
import java.util.HashMap;
import java.util.LinkedList;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String initial_state = sc.nextLine();
String final_state = sc.nextLine();
System.out.println(BFS(initial_state, final_state));
}
private static int BFS(String initial_state, String final_state) {
if (initial_state == final_state) {
return 0;
}
int[][] move_direction = {{0, -1}, {-1, 0}, {0, 1}, {1, 0}};
Deque<String> queue_1 = new LinkedList<String>();
Deque<String> queue_2 = new LinkedList<String>();
HashMap<String, Integer> visited = new HashMap<String, Integer>();
HashMap<String, Integer> steps = new HashMap<String, Integer>();
queue_1.offerLast(initial_state);
queue_2.offerLast(final_state);
visited.put(initial_state, 1);
visited.put(final_state, 2);
steps.put(initial_state, 0);
steps.put(final_state, 0);
while (!queue_1.isEmpty() && !queue_2.isEmpty()) {
String current_string;
int flag = 0;
if (queue_1.size() < queue_2.size()) {
flag = 1;
current_string = queue_1.peekFirst();
queue_1.pollFirst();
}
else {
flag = 2;
current_string = queue_2.peekFirst();
queue_2.pollFirst();
}
int index = 0;
for (int i = 0; i < current_string.length(); i++) {
if (current_string.charAt(i) == '.') {
index = i;
break;
}
}
int x = index / 3;
int y = index % 3;
for (int i = 0; i < 4; i++) {
int temp_x = x + move_direction[i][0];
int temp_y = y + move_direction[i][1];
if (temp_x >= 0 && temp_x < 3
&& temp_y >= 0 && temp_y < 3) {
int new_index = temp_x * 3 + temp_y;
char[] arr = current_string.toCharArray();
char temp_char = arr[new_index];
arr[new_index] = arr[index];
arr[index] = temp_char;
String new_string = new String(arr);
if (!visited.containsKey(new_string)) {
if (flag == 1) {
queue_1.offerLast(new_string);
}
else {
queue_2.offerLast(new_string);
}
visited.put(new_string, flag);
steps.put(new_string, steps.get(current_string) + 1);
}
else if (visited.get(current_string) + visited.get(new_string) == 3){
return (steps.get(current_string) + steps.get(new_string) + 1);
}
}
}
}
return -1;
}
}
参考思路: