Sliding Puzzle II
Description
中文English
On a 3x3 board, there are 8 tiles represented by the integers 1 through 8, and an empty square represented by 0.
A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.
Given an initial state of the puzzle board and final state, return the least number of moves required so that the initial state to final state.
If it is impossible to move from initial state to final state, return -1.
Example
Example 1:
Input:
[
[2,8,3],
[1,0,4],
[7,6,5]
]
[
[1,2,3],
[8,0,4],
[7,6,5]
]
Output:
4
Explanation:
[ [
[2,8,3], [2,0,3],
[1,0,4], --> [1,8,4],
[7,6,5] [7,6,5]
] ]
[ [
[2,0,3], [0,2,3],
[1,8,4], --> [1,8,4],
[7,6,5] [7,6,5]
] ]
[ [
[0,2,3], [1,2,3],
[1,8,4], --> [0,8,4],
[7,6,5] [7,6,5]
] ]
[ [
[1,2,3], [1,2,3],
[0,8,4], --> [8,0,4],
[7,6,5] [7,6,5]
] ]
Example 2:
Input:
[[2,3,8],[7,0,5],[1,6,4]]
[[1,2,3],[8,0,4],[7,6,5]]
Output:
-1
Challenge
- How to optimize the memory?
- Can you solve it with A* algorithm?
public class Solution {
/**
* @param init_state: the initial state of chessboard
* @param final_state: the final state of chessboard
* @return: return an integer, denote the number of minimum moving
*/
public int minMoveStep(int[][] init_state, int[][] final_state) {
// # write your code here
String source = matrixToString(init_state);
String target = matrixToString(final_state);
Queue<String> queue = new LinkedList<>();
Set<String> visited = new HashSet<>();
queue.offer(source);
visited.add(source);
int step = 0;
while(!queue.isEmpty()) {
int size = queue.size();
for(int i = 0; i < size; i++) {
String cur = queue.poll();
if(cur.equals(target)) return step;
for(String next : getNextState(cur)) {
if(!visited.contains(next)) {
queue.offer(next);
visited.add(next);
}
}
}
step++;
}
return -1;
}
public String matrixToString(int[][] matrix) {
StringBuilder sb = new StringBuilder();
for(int i = 0; i < 3; i++) {
for(int j = 0; j < 3; j++) {
sb.append(matrix[i][j]);
}
}
return sb.toString();
}
public List<String> getNextState(String curState) {
List<String> res = new ArrayList<>();
int zeroIndex = curState.indexOf('0');
int zx = zeroIndex / 3;
int zy = zeroIndex % 3;
int[] dx = {0, 0, 1, -1};
int[] dy = {1, -1, 0, 0};
for(int i = 0; i < 4; i++) {
int nx = zx + dx[i];
int ny = zy + dy[i];
if(0 <= nx && nx < 3 && 0 <= ny && ny < 3) {
char[] sc = curState.toCharArray();
// swap
sc[zx * 3 + zy] = sc[nx * 3 + ny];
sc[nx * 3 + ny] = '0';
res.add(new String(sc));
}
}
return res;
}
}