LeetCode 52 N-Queens II (C++, Python)

Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.


Solution C++


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
    bool isValid(int board[], int row) {
        for (int i = 0; i < row; ++i) {
            if (board[i] == board[row]) return false;
            if (abs(board[i] - board[row]) == row - i) return false;
        }
        return true;
    }
    void nQueen(int n, int row, int board[], int& ret) {
        if (row == n) {
            ret ++;
        } else {
            for (int i = 0; i < n; ++i) {
                board[row] = i;
                if (isValid(board, row)) {
                    nQueen(n, row + 1, board, ret);
                }
            }
        }
    }
public:
    int totalNQueens(int n) {
        int board[n];
        for (int i = 0; i < n; ++i) {
            board[n] = -1;
        }
        int ret = 0;
        nQueen(n, 0, board, ret);
        return ret;
    }
};

Solution Python


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Solution:
    def isValid(self, board, row):
        for i in range(row):
            if board[i] == board[row]: return False
            if abs(board[i] - board[row]) == row - i: return False
        return True
    def nQueens(self, row, board, ret):
        if row == len(board):
            ret[0] += 1
        else:
            for i in range(len(board)):
                board[row] = i
                if self.isValid(board, row):
                    self.nQueens(row + 1, board, ret)
    # @return a list of lists of string
    def totalNQueens(self, n):
        ret = [0]
        board = [-1] * n
        self.nQueens(0, board, ret)
        return ret[0]

Popular posts from this blog

How Django Works (4) URL Resolution

Python Class Method and Class Only Method

How Django works (3): Testing Server and Static Files Serving