class Solution{
Map<String, Integer> resMap = new HashMap();
int[][] steps = {{0, 1}, {0, - 1},{1, 0}, {-1, 0}};
class State{
int[][] state;
int x;
int y;
int step_count;
public State(int[][] state, int x, int y, int step_count) {
this.state = state;
this.x = x;
this.y = y;
this.step_count = step_count;
}
}
public int slidingPuzzle(int[][] board) {
int x_p = 0;
int y_p = 0;
for (int i = 0; i < 2; i++){
for (int j = 0; j < 3; j++){
if(board[i][j] == 0){
x_p = i;
y_p = j;
}
}
}
bfs(board, x_p, y_p);
return resMap.getOrDefault("123450", -1);
}
private void bfs(int[][] board, int x_p, int y_p) {
if (board2String(board).equals("123450")){
resMap.put("123450", 0);
return;
}
Queue<State> queue = new LinkedList<>();
queue.offer(new State(board.clone(),x_p, y_p, 0));
while (!queue.isEmpty()){
State s = queue.poll();
x_p = s.x;
y_p = s.y;
int count = s.step_count + 1;
//每次走一步
for (int[] step:
steps){
board = new int[2][3];
for (int i = 0; i < 2; i++)
for(int j = 0; j < 3; j++)
board[i][j] = s.state[i][j];
// System.arraycopy(s.state[i], 0, board[i], 0, 3);
if (x_p + step[0] < 0 || x_p + step[0] > 1
||y_p + step[1] < 0 || y_p + step[1] > 2){
continue;
}
swap(board,x_p,y_p,x_p + step[0], y_p + step[1]);
String tmp_state = board2String(board);
if (resMap.get(tmp_state) == null || resMap.get(tmp_state) > count){
resMap.put(tmp_state, count);
queue.offer(new State(board,x_p + step[0], y_p + step[1],count));
}
}
}
}
private void swap(int[][] board, int x_p, int y_p, int des_x, int des_y){
int t = board[x_p][y_p];
board[x_p][y_p] = board[des_x][des_y];
board[des_x][des_y] = t;
}
private String board2String(int[][] board){
StringBuilder res = new StringBuilder();
for (int i = 0; i < 2; i++){
for (int j = 0; j < 3; j++){
res.append(board[i][j]);
}
}
return res.toString();
}
}
What I want to note:
一開始打算用DFS鲫懒,發(fā)現每次DFS前后都要維護狀態(tài)翰意,且不符合題意棒假。題意是說最少的步數蜡饵,DFS
適合最大值以及有明確邊界條件的問題或者換一種說法DFS
是一種和最大以及回溯和剪枝有關的解法;而BFS
確是和最小有關可無邊界的最小值問題黔夭。