N-Queens

Posted by Bill on November 13, 2023

N-Queens

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

Given an integer n, return all distinct solutions to the n-queens puzzle. You may return the answer in any order.

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Example 1:


Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:

Input: n = 1
Output: [["Q"]]


Constraints:

1 <= n <= 9

Solution

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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
class Solution {
  private:
  vector<vector<string>> res;
  unordered_set<int> colSet;
  unordered_set<int> diag1Set;
  unordered_set<int> diag2Set;

  public:
  bool checkVec(int row, int col) {
    // Check column conflicts
    if (colSet.count(col) > 0) {
      return false;
    }

    // Check diagonal conflicts
    if (diag1Set.count(row + col) > 0 || diag2Set.count(row - col) > 0) {
      return false;
    }
    return true;
  }
  void solveNQueensImpl(int row, int n, vector<int> board) {
    if (row == n) {
      vector<string> tmpVec;
      for (int i = 0; i < n; i++) {
        string tmp(n, '.');
        tmp[board[i]] = 'Q';
        tmpVec.push_back(tmp);
      }
      res.push_back(tmpVec);
      return;
    }

    for (int col = 0; col < n; col++) {
      if (checkVec(row, col)) {
        board[row] = col;
        colSet.insert(col);
        diag1Set.insert(row + col);
        diag2Set.insert(row - col);

        solveNQueensImpl(row + 1, n, board);

        colSet.erase(col);
        diag1Set.erase(row + col);
        diag2Set.erase(row - col);
      }
    }
  }
  vector<vector<string>> solveNQueens(int n) {
    vector<int> board(n, 0);
    solveNQueensImpl(0, n, board);
    return res;
  }
};