LeetCode 51 N-Queeens (C++, Python)

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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
 [".Q..",  // Solution 1
  "...Q",
  "Q...",
  "..Q."],

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

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
32
33
34
35
36
37
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[], vector<vector<string>>& ret) {
        if (row == n) {
            vector<string> sol;
            for (int i = 0; i < n; ++i) {
                string tmp(n, '.');
                tmp[board[i]] = 'Q';
                sol.push_back(tmp);
            }
            ret.push_back(sol);
        } else {
            for (int i = 0; i < n; ++i) {
                board[row] = i;
                if (isValid(board, row)) {
                    nQueen(n, row + 1, board, ret);
                }
            }
        }
    }
public:
    vector<vector<string> > solveNQueens(int n) {
        vector<vector<string>> ret;
        int board[n];
        for (int i = 0; i < n; ++i) {
            board[n] = -1;
        }
        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
21
22
23
24
25
26
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):
            sol = []
            for i in range(len(board)):
                tmp = ['.'] * len(board)
                tmp[board[i]] = 'Q'
                sol.append(''.join(tmp))
            ret.append(sol)
        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 solveNQueens(self, n):
        ret = []
        board = [-1] * n
        self.nQueens(0, board, ret)
        return ret
        

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