[LeetCode] 51. N-Queens

Problem

The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

Given an integer n, return all distinct solutions to the n-queens puzzle.

Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

Example:


Input: 4
Output: [
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.

Solution

class Solution {
    public List> solveNQueens(int n) {
        char[][] board = new char[n][n];
        for (int i = 0; i < n; i++) {
            Arrays.fill(board[i], '.');
        }
        List> res = new ArrayList<>();
        dfs(board, 0, res);
        return res;
    }
    
    private void dfs(char[][] board, int col, List> res) {
        if (col == board.length) {
            res.add(construct(board));
            return;
        }
        
        for (int row = 0; row < board.length; row++) {
            if (validate(board, row, col)) {
                board[row][col] = 'Q';
                dfs(board, col+1, res);
                board[row][col] = '.';
            }
        }
    }
    
    private boolean validate(char[][] board, int row, int col) {
        for (int i = 0; i < board.length; i++) {
            for (int j = 0; j < col; j++) {
                if (board[i][j] == 'Q' && (
                    i+j == row+col || row+j == col+i || row == i
                )) return false;
            }
        }
        
        return true;
    }
    
    private List construct(char[][] board) {
        List res = new ArrayList<>();
        for (int i = 0; i < board.length; i++) {
            String str = new String(board[i]);
            res.add(str);
        }
        return res;
    }
}

你可能感兴趣的:(dfs,matrix,string,数组)