forked from mahendrarathore1742/leetcode-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathleetcode0051-n-queens.cpp
42 lines (40 loc) · 1.29 KB
/
leetcode0051-n-queens.cpp
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
/*
* Copyright (C) 2018 all rights reserved.
*
* Author: Houmin Wei <[email protected]>
*
* Source: https://leetcode.com/problems/n-queens
*/
#include <string>
#include <vector>
using namespace std;
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<string> board(n, string(n, '.'));
vector<vector<string>> ret;
vector<bool> row(n, false);
vector<bool> lefttop(2*n-1, false);
vector<bool> righttop(2*n-1, false);
queen(0, n, board, ret, row, lefttop, righttop);
return ret;
}
void queen(int column, int n, vector<string>& board, vector<vector<string>>& ret, vector<bool>& row, vector<bool>& lefttop, vector<bool>& righttop) {
if (column == n) {
ret.push_back(board);
return;
}
for (int i = 0; i < n; i++) {
if (row[i] || lefttop[column-i+n-1] || righttop[i+column]) continue;
row[i] = true;
lefttop[column-i+n-1] = true;
righttop[i+column] = true;
board[i][column] = 'Q';
queen(column+1, n, board, ret, row, lefttop, righttop);
board[i][column] = '.';
row[i] = false;
lefttop[column-i+n-1] = false;
righttop[i+column] = false;
}
}
};