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.."] ]
C++:
class Solution {
public:
void print(int queue[], int n, vector<vector<string>> &qipan) {
int i, j;
/*for(i = 0; i < n; i++) {
printf("row :%d, col :%d\n", i , queue[i]);
} */
vector<string> method;
for(i = 0; i < n; i++) {
string str(n,'.');
str[queue[i]] = 'Q';
method.push_back(str);
}
//printf("\n");
qipan.push_back(method);
//printf("\n");
}
void testQueue(int queue[], int row, int n, vector<vector<string>> &qipan) {
int j, k;
if(row >= n) print(queue, n, qipan);
else {
for(j = 0; j < n; j++) {
queue[row] = j;
for(k = 0; k < row; k++) {
if((queue[k] - queue[row]) * (fabs(queue[k] - queue[row]) - fabs(k - row)) == 0) {
break;
}
if(k == row - 1) testQueue(queue, row + 1, n, qipan);
}
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> qipan;
int queue[n];
int i;
for(i = 0; i < n; i++ ) queue[i] = -1;
for(i = 0; i < n; i++) {
//printf("method :\n");
queue[0] = i;
testQueue(queue, 1, n, qipan);
}
return qipan;
}
};
C:
#include<stdio.h>
#include<math.h>
#define N 1
char qipan[100][N][N];
static int index = 0;
void print(int queue[], int n) {
int i, j;
for(i = 0; i < n; i++) {
printf("row :%d, col :%d\n", i , queue[i]);
}
for(i = 0; i < n; i++) {
for(j = 0; j < n; j++) {
if(queue[i] == j)
qipan[index][i][j] = 'Q';
else qipan[index][i][j] = '.';
printf("%c ", qipan[index][i][j]);
}
printf("\n");
}
printf("\n");
}
void testQueue(int queue[], int row, int n) {
int j, k;
if(row >= n) print(queue, n);
else {
for(j = 0; j < n; j++) {
queue[row] = j;
for(k = 0; k < row; k++) {
if((queue[k] - queue[row]) * (fabs(queue[k] - queue[row]) - fabs(k - row)) == 0) {
break;
}
if(k == row - 1) testQueue(queue, row + 1, n);
}
}
}
}
void solveNQueens(int n) {
int queue[n];
int i;
for(i = 0; i < n; i++ ) queue[i] = -1;
for(i = 0; i < n; i++) {
printf("method :\n");
queue[0] = i;
testQueue(queue, 1, n);
}
}
void main() {
solveNQueens(N);
}