题目地址:
https://www.lintcode.com/problem/sliding-puzzle/description
给定一个 2 2 2行 3 3 3列的整型矩阵,每一位恰好是 0 ∼ 5 0\sim 5 0∼5,每一步允许将其中的 0 0 0与四个方向的数字进行交换。给定初始状态,问要经过多少步可以达到 [ [ 1 , 2 , 3 ] , [ 4 , 5 , 0 ] ] [[1,2,3],[4,5,0]] [[1,2,3],[4,5,0]]这个状态。
实际上就是隐式图的最短路问题,可以用BFS来求解。问题的关键在于存储状态。我们可以将二维矩阵序列化为字符串存储,这样判重和存储都很方便。代码如下:
import java.util.*;
public class Solution {
/**
* @param board: the given board
* @return: the least number of moves required so that the state of the board is solved
*/
public int slidingPuzzle(int[][] board) {
// write your code here
// 将初始状态序列化为字符串
StringBuilder sb = new StringBuilder();
for (int i = 0; i < board.length; i++) {
for (int j = 0; j < board[0].length; j++) {
sb.append(board[i][j]);
}
}
String start = sb.toString();
String end = "123450";
// 如果初始状态就等于目标状态了,直接返回0
if (start.equals(end)) {
return 0;
}
Queue<String> queue = new LinkedList<>();
queue.offer(start);
Set<String> visited = new HashSet<>();
visited.add(start);
// res记录操作步数
int res = 0;
while (!queue.isEmpty()) {
res++;
// 由于要分层BFS,需要记录队列的size
int size = queue.size();
for (int i = 0; i < size; i++) {
String cur = queue.poll();
// 得到从cur走一步可以到达的未访问过的状态,
// 一旦发现到达了目标状态就返回步数
for (String next : getNexts(cur, visited)) {
if (next.equals(end)) {
return res;
}
visited.add(next);
queue.offer(next);
}
}
}
// 到不了则返回-1
return -1;
}
private List<String> getNexts(String cur, Set<String> visited) {
StringBuilder state = new StringBuilder(cur);
int[] d = {1, 0, -1, 0, 1};
int x = 0, y = 0;
// 先找到0所在的位置
for (int i = 0; i < cur.length(); i++) {
if (cur.charAt(i) == '0') {
x = i / 3;
y = i % 3;
break;
}
}
List<String> nexts = new ArrayList<>();
// 遍历四个方向
for (int i = 0; i < 4; i++) {
int nextX = x + d[i], nextY = y + d[i + 1];
if (0 <= nextX && nextX < 2 && 0 <= nextY && nextY < 3) {
int swapPosition = nextX * 3 + nextY;
// 将state的两个位置进行交换,得到新的状态,如果之前没访问过就加入列表
swap(state, getPos(x, y), getPos(nextX, nextY));
String nextState = state.toString();
if (!visited.contains(nextState)) {
nexts.add(nextState);
}
// 加完了还需要变回来,以便寻找下一个可行的状态
swap(state, getPos(x, y), getPos(nextX, nextY));
}
}
return nexts;
}
// 将二维坐标与一维坐标建立对应关系
private int getPos(int x, int y) {
return x * 3 + y;
}
// 交换sb的第i和第j个字符
private void swap(StringBuilder sb, int i, int j) {
char tmp = sb.charAt(i);
sb.setCharAt(i, sb.charAt(j));
sb.setCharAt(j, tmp);
}
}
本质上搜索空间状态数量不会超过 O ( 6 ! ) O(6!) O(6!),所以也可以认为时空复杂度是 O ( 1 ) O(1) O(1)。