跳转至

52. N-Queens II

Leetcode Backtracking

题目

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

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

Example:

Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

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

分析

直接计算51. N-Queens结果大小即可。

private int count;
public int totalNQueens(int n) {
    if (n <= 0) return 0;
    count = 0;
    char[][] board = new char[n][n];
    for (int i = 0; i < n; i++)
        for (int j = 0; j < n; j++)
            board[i][j] = '.';
    solveNQueens(board, 0);
    return count;
}

private void solveNQueens(char[][] board, int col){
    int n = board.length;
    // base case
    if (col == n) {
        count++;
        return;
    }
    for (int i = 0; i < n; i++) {
        if (isSafe(board, i, col)) {
            board[i][col] = 'Q';
            solveNQueens(board, col + 1);
            board[i][col] = '.';
        } // end if
    } // end for
}