[LeetCode] 773. 滑动谜题

朴素的BFS,注意要考虑输入就是答案的情况

class Solution {
    class State {
        int[][] board;
        int p;
        int q;
        int cnt;

        State(int[][] b, int i, int j) {
            board = b;
            p = i;
            q = j;
            cnt = 0;
        }

        State(int[][] b, int i, int j, int c) {
            board = b;
            p = i;
            q = j;
            cnt = c;
        }
    }

    public int slidingPuzzle(int[][] board) {

        if (toString(board).equals("123450")) return 0;
        int i = 0;
        int j = 0;
        for (int p = 0; p < 2; p++) {
            for (int q = 0; q < 3; q++) {
                if (board[p][q] == 0) {
                    i = p;
                    j = q;
                    break;
                }
            }
        }

        Queue<State> queue = new ArrayDeque<>();
        queue.add(new State(board, i, j));

        Set<String> visited = new HashSet<>();
        visited.add(toString(board));

        while (!queue.isEmpty()) {
            State poll = queue.poll();

            int p = poll.p;
            int q = poll.q;
            int cnt = poll.cnt;
            for (int k = 1; k <= 4; k++) {
                int[][] nextBoard = new int[2][3];
                nextBoard[0] = Arrays.copyOf(poll.board[0], poll.board[0].length);
                nextBoard[1] = Arrays.copyOf(poll.board[1], poll.board[1].length);
                int nextP = p;
                int nextQ = q;

                switch (k) {
                    case 1:
                        if (p - 1 >= 0) {
                            nextP = p - 1;
                        }
                        break;
                    case 2:
                        if (p + 1 < 2) {
                            nextP = p + 1;
                        }
                        break;
                    case 3:
                        if (q - 1 >= 0) {
                            nextQ = q - 1;
                        }
                        break;
                    case 4:
                        if (q + 1 < 3) {
                            nextQ = q + 1;
                        }
                        break;
                }
                nextBoard[p][q] = nextBoard[nextP][nextQ];
                nextBoard[nextP][nextQ] = 0;
                String s = toString(nextBoard);
                if (s.equals("123450")) return cnt + 1;
                if (!visited.contains(s)){
                    visited.add(s);
                    queue.add(new State(nextBoard, nextP, nextQ, cnt + 1));

                }
            }
        }

        return -1;
    }

    private String toString(int[][] board) {
        return "" + board[0][0] + board[0][1] + board[0][2] + board[1][0] + board[1][1] + board[1][2];
    }
}
posted @ 2021-06-29 23:29  ACBingo  阅读(33)  评论(0编辑  收藏  举报