In chess, queens can attack pawns on their rows, columns, and diagonals. The N-queen problem is to place N queens on a chessboard with N rows and N columns, so that the queens must not be attacked, that is, any two queens are not in the same row, column and diagonal of the system.
To solve this problem, consider backtracking: place the ith queen on the ith row, then start with the first queen, and for each queen, start from the first of its corresponding row (the ith queen corresponds to the ith row) The column starts to try to be placed. If it can be placed, the position is determined and the next queen is considered; if it conflicts with the previous queen, the next column is considered; if the last column is exceeded, the position of the previous queen is re-determined. Repeat the process until all placement scenarios are found.
Below is the C++ code implementation of the algorithm.
Constant and Variable Description
pos: One-dimensional array, pos[i] indicates the specific position where the i-th queen is placed in the i-th row
count: count the number of placement plans
N: number of queens
C++ code:
#include "stdafx.h"
#include <iostream>
int isPlace(int pos[], int k);
int main() {
const int N = 4;
int i, j, count = 1;
int pos[N + 1];
//initialize position
for (i = 1; i <= N; i++) {
pos[i] = 0;
}
j = 1;
while (j >= 1) {
pos[j] = pos[j] + 1;
//try to place the i-th queen
while (pos[j] <= N && isPlace(pos, j) == 0) {
pos[j] = pos[j] + 1;
}
// get a placement plan
if (pos[j] <= N && j == N) {
printf("Program%d:", count++);
for (i = 1; i <= N; i++) {
printf("%d-", pos[i]);
}
printf("\n");
}
// consider the next queen
if (pos[j] <= N && j < N) {
j = j + 1;
}
else {//Return to consider the previous queen
pos[j] = 0;
j = j - 1;
}
}
system("pause");
return 1;
}
int isPlace(int pos[], int k) {
for (int i = 1; i < k; i++) {
if (pos[i] == pos[k] || fabs(i - k) == fabs(pos[i] - pos[k])) {
return 0;
}
}
return 1;
}