n皇后问题

2018-10-26 23:13:41

问题描述:

问题求解:

n皇后问题是一个经典的递归求解的问题,主要的trick就是将对角线元素用数组来进行记录是否使用过。

    public List<List<String>> solveNQueens(int n) {
        List<List<String>> res = new ArrayList<>();
        char[][] board = new char[n][n];
        for (int i = 0; i < n; i++) Arrays.fill(board[i], '.');
        int[] col = new int[n];
        int[] diag1 = new int[2 * n - 1];
        int[] diag2 = new int[2 * n - 1];
        helper(board, n, 0, col, diag1, diag2, res);
        return res;
    }

    private void helper(char[][] board, int n, int row, int[] col, int[] diag1, int[] diag2, List<List<String>> res) {
        if (row == n) {
            List<String> tmp = new ArrayList<>();
            for (int i = 0; i < n; i++) tmp.add(new String(board[i]));
            res.add(tmp);
            return;
        }
        for (int i = 0; i < n; i++) {
            if (isValid(row, i, n, col, diag1, diag2)) {
                put(board, row, i, n, col, diag1, diag2);
                helper(board, n, row + 1, col, diag1, diag2, res);
                remove(board, row, i, n, col, diag1, diag2);
            }
        }
    }

    private boolean isValid(int x, int y, int n, int[] col, int[] diag1, int[] diag2) {
        return col[y] == 0 && diag1[x + y] == 0 && diag2[n - 1 + y - x] == 0;
    }

    private void put(char[][] board, int x, int y, int n, int[] col, int[] diag1, int[] diag2) {
        board[x][y] = 'Q';
        col[y] = 1;
        diag1[x + y] = 1;
        diag2[n - 1 + y - x] = 1;
    }

    private void remove(char[][] board, int x, int y, int n, int[] col, int[] diag1, int[] diag2) {
        board[x][y] = '.';
        col[y] = 0;
        diag1[x + y] = 0;
        diag2[n - 1 + y - x] = 0;
    }

 

posted @ 2018-10-26 23:21  hyserendipity  阅读(204)  评论(0编辑  收藏  举报