-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode_51.cpp
More file actions
98 lines (92 loc) · 2.42 KB
/
LeetCode_51.cpp
File metadata and controls
98 lines (92 loc) · 2.42 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#include <iostream>
#include <vector>
using namespace std;
typedef vector<string> vs;
typedef vector<vs> vvs;
#define _CRT_SECURE_NO_DEPRECATE
#define __elshorpagi__ (ios_base::sync_with_stdio(false), cin.tie(NULL))
#define edl '\n'
#define fr(i, x, n) for (int i(x); i < n; ++i)
#define fc(it, v) for (auto &(it) : (v))
class Solution
{
vs chess_board;
public:
Solution() { __elshorpagi__; }
bool is_valid(int row, int col, int n)
{
// check this row on the left side
fr(i, 0, col)
{
if (chess_board[row][i] == 'Q')
return false;
}
// check the upper diagonal on the left side
for (int i(row), j(col); i > -1 && j > -1; --i, --j)
{
if (chess_board[i][j] == 'Q')
return false;
}
// check the lower diagonal on the left side
for (int i(row), j(col); i < n && j > -1; ++i, --j)
{
if (chess_board[i][j] == 'Q')
return false;
}
return true;
}
void backtracking(vvs &ans, int col, int n)
{
if (col == n)
ans.push_back(chess_board);
else
{
fr(row, 0, n)
{
if (is_valid(row, col, n))
{
chess_board[row][col] = 'Q'; // update the state
backtracking(ans, col + 1, n);
chess_board[row][col] = '.'; // undo the state
}
}
}
}
vvs solveNQueens(int n)
{
chess_board = vs(n, string(n, '.'));
vvs ans;
backtracking(ans, 0, n);
return ans;
}
void TEST()
{
int n(4);
vvs result = solveNQueens(n);
fc(it, result)
{
fc(jt, it) { cout << jt << ' '; }
// [[".Q..", "...Q", "Q...", "..Q."], ["..Q.", "Q...", "...Q", ".Q.."]]
cout << edl;
}
cout << edl << "********************" << edl << edl;
n = 1, result = solveNQueens(n);
fc(it, result)
{
fc(jt, it) { cout << jt << ' '; } // [["Q"]]
cout << edl;
}
}
};
int main()
{
Solution sol;
// freopen("../test/input.txt", "r", stdin);
freopen("../test/output.txt", "w", stdout);
int tc(1);
// cin >> tc;
while (tc--)
cout << "Case #" << tc + 1 << edl, sol.TEST();
cout << edl << "DONE" << edl;
return (0);
}