51. N-Queens

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

51. N-Queens_第1张图片

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.
For example,There exist two distinct solutions to the 4-queens puzzle:

[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

 ["..Q.",  // Solution 2
  "Q...",
  "...Q",
  ".Q.."]
]

一刷
题解:
任两个皇后都不能处于同一条横行、纵行或斜线上。DFS求解,注意check board是否validate的条件:board[i][j] == 'Q' && (x + j == y + i || x + y == i + j || x == i)

public class Solution {
    public List> solveNQueens(int n) {
        List> res = new ArrayList<>();
        char[][] board = new char[n][n];
        for(int i=0; i> res) {
        if(colIndex == board.length) {
            res.add(construct(board));
            return;
        }
        
        for(int i = 0; i < board.length; i++) {
            if(validate(board, i, colIndex)) {
                board[i][colIndex] = 'Q';
                dfs(board, colIndex + 1, res);
                board[i][colIndex] = '.';
            }
        }
    }
    
    private boolean validate(char[][] board, int x, int y) {
        for(int i = 0; i < board.length; i++) {
            for(int j = 0; j < y; j++) {
                if(board[i][j] == 'Q' && (x + j == y + i || x + y == i + j || x == i))//
                    return false;
            }
        }
        
        return true;
    }
    
    
    private List construct(char[][] board){
        List res = new LinkedList();
        for(int i=0; i

你可能感兴趣的:(51. N-Queens)