aboutsummaryrefslogtreecommitdiff
path: root/n_queens.cpp
blob: df2457ee0446d14b613f3fab4c2d276cba260e2f (plain)
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
#include "leetcode.h"

class Solution {
public:
  vector<vector<string>> solveNQueens(int n) {
    vector<vector<string>> ans;
    vector<string> nQueens(n, string(n, '.'));
    solve(ans, nQueens, 0, n);
    return ans;
  }

private:
  void solve(vector<vector<string>> &ans, vector<string> &nQueens, int row,
             int &n) {
    if (row == n) {
      ans.push_back(nQueens);
      return;
    }
    for (int col = 0; col != n; ++col)
      if (isValid(nQueens, row, col, n)) {
        nQueens[row][col] = 'Q';
        solve(ans, nQueens, row + 1, n);
        nQueens[row][col] = '.';
      }
  }
  bool isValid(vector<string> &nQueens, int row, int col, int &n) {
    // check if col had queen
    for (int i = 0; i != row; ++i)
      if (nQueens[i][col] == 'Q')
        return false;
    // check if 45deg diagonal had queen
    for (int i = row - 1, j = col - 1; i >= 0 && j >= 0; --i, --j)
      if (nQueens[i][j] == 'Q')
        return false;
    // check if 135deg diagonal had queen
    for (int i = row - 1, j = col + 1; i >= 0 && j < n; --i, ++j)
      if (nQueens[i][j] == 'Q')
        return false;
    return true;
  }
};

int main() {}