-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path51NQueens.cpp
More file actions
80 lines (67 loc) · 1.67 KB
/
51NQueens.cpp
File metadata and controls
80 lines (67 loc) · 1.67 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//
// Created by ys on 2020/10/18.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
vector<vector<string>> res;
public:
vector<vector<string>> solveNQueens(int n) {
vector<string> board(n, string(n,'.'));
backtrace(board, 0);
return res;
}
void backtrace(vector<string> board, int row)
{
if(board.size()==row)
{
res.push_back(board);
return;
}
for (int col = 0; col < board.size(); ++col)
{
if(!isvalid(board, row, col))
continue;
board[row][col] = 'Q';
backtrace(board, row+1);
board[row][col] = '.';
}
}
bool isvalid(vector<string> board, int row, int col)
{
for (int i = 0; i < row; ++i)
{
if(board[i][col]=='Q')
return false;
}
for (int i=row-1, j=col-1;i>=0&&j>=0;--i,--j)
{
if(board[i][j]=='Q')
return false;
}
int n = board.size();
for (int i = row-1, j = col+1; i >=0 && j < n; --i, ++j)
{
if(board[i][j]=='Q')
return false;
}
return true;
}
void printBoard()
{
int n = res.size();
for (int i = 0; i < n; ++i)
{
for (int j = 0; j < res[0].size(); ++j)
{
for (int k = 0; k < res[0].size(); ++k)
{
cout << res[i][j][k];
}
cout << endl;
}
cout << "------------------------------------------------------"<< endl;
}
}
};