forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnQueuens.cpp
118 lines (95 loc) · 2.85 KB
/
nQueuens.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
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
// Source : https://oj.leetcode.com/problems/n-queens/
// Author : Hao Chen
// Date : 2014-08-22
/**********************************************************************************
*
* The n-queens puzzle is the problem of placing n queens on an n×n chessboard
* such that no two queens attack each other.
*
* Given an integer n, return all distinct solutions to the n-queens puzzle.
*
* Each solution contains a distinct board configuration of the n-queens' placement,
* where 'Q' and '.' both indicate a queen and an empty space respectively.
*
* For example,
* There exist two distinct solutions to the 4-queens puzzle:
*
* [
* [".Q..", // Solution 1
* "...Q",
* "Q...",
* "..Q."],
*
* ["..Q.", // Solution 2
* "Q...",
* "...Q",
* ".Q.."]
* ]
*
*
**********************************************************************************/
#include <stdlib.h>
#include <iostream>
#include <vector>
#include <string>
using namespace std;
vector< vector<string> > solveNQueens(int n);
void solveNQueensRecursive(int n, int currentRow, vector<int>& solution, vector< vector<string> >& result);
bool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn);
vector< vector<string> > solveNQueens(int n) {
vector< vector<string> > result;
vector<int> solution(n);
solveNQueensRecursive(n, 0, solution, result);
return result;
}
void solveNQueensRecursive(int n, int currentRow, vector<int>& solution, vector< vector<string> >& result) {
if (currentRow == n){
vector<string> s;
for (int i = 0; i < n; i++) {
string row;
for (int j = 0; j < n; j++) {
if ( solution[i]== j ) {
row += "Q";
}else{
row += ".";
}
}
s.push_back(row);
}
result.push_back(s);
return;
}
for (int i = 0; i < n; i++) {
if (isValid(i, currentRow, solution) ) {
solution[currentRow] = i;
solveNQueensRecursive(n, currentRow+1, solution, result);
}
}
}
bool isValid(int attemptedColumn, int attemptedRow, vector<int> &queenInColumn) {
for(int i=0; i<attemptedRow; i++) {
if (attemptedColumn == queenInColumn[i] ||
abs(attemptedColumn - queenInColumn[i]) == abs(attemptedRow - i)) {
return false;
}
}
return true;
}
void printMatrix(vector< vector<string> >& matrix ){
for (int i = 0; i < matrix.size(); i++) {
cout << "-----------" << endl;
for (int j = 0; j < matrix[i].size(); j++) {
cout << matrix[i][j] << endl;
}
}
}
int main(int argc, char** argv)
{
int n = 8;
if (argc>1){
n = atoi(argv[1]);
}
vector< vector<string> > result = solveNQueens(n);
printMatrix(result);
return 0;
}