JIAKAOBO

LeetCode

venmo
wechat

感谢赞助!

  • ㊗️
  • 大家
  • offer
  • 多多!

Problem

On a 2x3 board, there are 5 tiles represented by the integers 1 through 5, and an empty square represented by 0.

A move consists of choosing 0 and a 4-directionally adjacent number and swapping it.

The state of the board is solved if and only if the board is [[1,2,3],[4,5,0]].

Given a puzzle board, return the least number of moves required so that the state of the board is solved. If it is impossible for the state of the board to be solved, return -1.

Examples:

Input: board = [[1,2,3],[4,0,5]]
Output: 1
Explanation: Swap the 0 and the 5 in one move.
Input: board = [[1,2,3],[5,4,0]]
Output: -1
Explanation: No number of moves will make the board solved.
Input: board = [[4,1,2],[5,0,3]]
Output: 5
Explanation: 5 is the smallest number of moves that solves the board.
An example path:
After move 0: [[4,1,2],[5,0,3]]
After move 1: [[4,1,2],[0,5,3]]
After move 2: [[0,1,2],[4,5,3]]
After move 3: [[1,0,2],[4,5,3]]
After move 4: [[1,2,0],[4,5,3]]
After move 5: [[1,2,3],[4,5,0]]
Input: board = [[3,2,4],[1,5,0]]
Output: 14

Code

class Solution {
    public int slidingPuzzle(int[][] board) {
        int row = board.length;
        int col = board[0].length;

        // 123450
        String goal = "";
        String start = "";

        for(int i = 0; i < row; i++) {
            for(int j = 0; j < col; j++) {
                start += board[i][j];
                goal += (i * col + j + 1) % (row * col);
            }
        }

        if (start.equals(goal)) return 0;

        int[][] dirs = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
        Queue<String> queue = new LinkedList<>();
        HashSet<String> visited = new HashSet<>();
        int step = 0;

        queue.offer(start);
        visited.add(start);

        while(!queue.isEmpty()) {
            int size = queue.size();
            for(int i = 0; i < size; i++) {
                String curr = queue.poll();
                if(curr.equals(goal)) return step;

                int p = curr.indexOf("0");
                int x = p / col;
                int y = p % col;

                for(int[] dir: dirs) {
                    int tx = x + dir[0];
                    int ty = y + dir[1];
                    if (tx < 0 || ty < 0 || tx >= row || ty >= col) continue;
                    int pp = ty + tx * col;
                    StringBuilder sb = new StringBuilder(curr);
                    sb.setCharAt(p, sb.charAt(pp));
                    sb.setCharAt(pp, '0');

                    String next = sb.toString();
                    if (visited.contains(next)) {
                        continue;
                    }
                    queue.offer(next);
                    visited.add(next);
                }

            }

            step++;
        }

        return -1;
    }
}
  • time: O((n * m)!)
  • space: O((n * m)!)