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 the number of distinct solutions to the n-queens puzzle.
Input: 4
Output: 2
Explanation: There are two distinct solutions to the 4-queens puzzle as shown below.
[
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
class Solution {
private:
bool checkConflict(int row, int col, vector<int> & columns) {
for (int r = 0; r < row; ++r) {
// a the same column of at the diagonal
if(columns[r] == col || row - r == abs(columns[r] - col))
return false;
}
return true;
}
void backTracking(int row, int n, vector<int>& columns, int & count) {
if(row == n) {
count++;
return;
}
// try to place che queen in the current row and check whether
// it is valid.
for(int col = 0; col < n; ++col) {
columns[row] = col;
if(checkConflict(row, col, columns))
backTracking(row + 1, n, columns, count);
columns[row] = -1;
}
}
public:
int totalNQueens(int n) {
int count = 0;
vector<int> columns(n, 0);
backTracking(0, n, columns, count);
return count;
}
};
The Time complexity
Assume T(N) is the time complexity for N Queen problem
It neet n*T(n-1) +n*n.
That is T(n) = n*T(n-1) +n^2
then T(n) = n*(n-1)*T(n-2) + n^2 + n*(n-1)^2
...T(n) = n*(n-1)*(n-2)*...*T(0) + = O(n!)
A final test solution:
#include <algorithm>
#include <iostream>
#include <list>
#include <queue>
#include <string>
#include <vector>
#include <stack>
using namespace std;
class Solution {
private:
bool checkConflict(int row, int col, vector<int> & columns) {
for (int r = 0; r < row; ++r) {
// a the same column of at the diagonal
if(columns[r] == col || row - r == abs(columns[r] - col))
return false;
}
return true;
}
void backTracking(int row, int n, vector<int>& columns,
vector<vector<int>> & results) {
if(row == n) {
results.push_back(columns);
return;
}
// try to place che queen in the current row and check whether
// it is valid.
for(int col = 0; col < n; ++col) {
columns[row] = col;
if(checkConflict(row, col, columns)) {
backTracking(row + 1, n, columns, results);
}
columns[row] = -1;
}
}
public:
vector<vector<int>> totalNQueens(int n) {
vector<vector<int>> results;
vector<int> columns(n, 0);
backTracking(0, n, columns, results);
return results;
}
void printQueen(int pos, int Total) {
for(int i = 0; i < Total; ++i) {
cout << (i == pos ? 'X' : ' ');
}
cout << endl;
}
void printResult(vector<vector<int>> & results) {
for(auto & solution : results) {
cout << "-----------------------------" << endl;
int n = solution.size();
for(int i = 0; i < n; ++i)
printQueen(solution[i], n);
cout << "-----------------------------" << endl;
}
}
};
int main()
{
Solution sol;
auto result = sol.totalNQueens(5);
sol.printResult(result);
return 0;
}