-
Notifications
You must be signed in to change notification settings - Fork 0
/
51.n皇后.cpp
60 lines (57 loc) · 1.25 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
/*
* @lc app=leetcode.cn id=51 lang=cpp
*
* [51] N皇后
*/
// @lc code=start
#include <vector>
#include <string>
#include <cmath>
using namespace std;
class Solution
{
public:
vector<vector<string>> solveNQueens(int n)
{
vector<vector<string>> res;
vector<string> tmp(n, string(n, '.'));
dfs(0, n, res, tmp);
return res;
}
void dfs(int row, int n, vector<vector<string>> &res, vector<string> tmp)
{
if (row == n)
{
res.push_back(tmp);
return;
}
for (size_t i = 0; i < n; i++)
{
if (match(tmp, row, i, n))
{
tmp[row][i] = 'Q';
dfs(row + 1, n, res, tmp);
tmp[row][i] = '.';
}
}
return;
}
bool match(vector<string> &tmp, int row, int col, int n)
{
for (int i = 0; i <= row; i++)
{
for (int j = 0; j < n; j++)
{
if (tmp[i][j] == 'Q')
{
if (abs(i - row) == abs(j - col) || j == col)
{
return false;
}
}
}
}
return true;
}
};
// @lc code=end