-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path51.n皇后.cpp
62 lines (57 loc) · 1.37 KB
/
51.n皇后.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
#include <string>
#include <vector>
using namespace std;
/*
* @lc app=leetcode.cn id=51 lang=cpp
*
* [51] N皇后
*/
// @lc code=start
class Solution {
private:
using board_type = vector<string>;
bool is_valid(int row, int col, const board_type& checkerboard) {
// check top
for (int irow = row, icol = col; irow >= 0; irow--) {
if (checkerboard[irow][icol] == 'Q') {
return false;
}
}
// check top-left
for (int irow = row, icol = col; icol >= 0 && irow >= 0; icol--, irow--) {
if (checkerboard[irow][icol] == 'Q') {
return false;
}
}
// check top-right
for (int irow = row, icol = col;
irow >= 0 && icol < checkerboard[irow].size(); irow--, icol++) {
if (checkerboard[irow][icol] == 'Q') {
return false;
}
}
return true;
}
public:
void dfs(int row, int n, board_type board, vector<board_type>& ans) {
if (row == n) {
ans.push_back(move(board));
return;
}
for (int col = 0; col < n; col++) {
if (is_valid(row, col, board)) {
board[row][col] = 'Q';
dfs(row + 1, n, board, ans);
board[row][col] = '.';
}
}
}
vector<board_type> solveNQueens(int n) {
vector<board_type> ans;
vector<string> board(n, string(n, '.'));
dfs(0, n, board, ans);
return ans;
}
};
// @lc code=end