八皇后问题是一个以国际象棋为背景的问题:如何能够在 8×8 的国际象棋棋盘上放置八个皇后,使得任何一个皇后都无法直接吃掉其他的皇后?为了达到此目的,任两个皇后都不能处于同一条横行、纵行或斜线上。
//八皇后-回溯法递归实现(学长提供的思路)
#include <cstdio>
using namespace std;
int q[8] = {};
void printQ(){
static int cnt = 1;
printf("%d:", cnt);
++cnt;
for(int i = 0; i < 8; i++){
printf(" %d", q[i]);
}
printf("\n");
}
int check(int row, int col){
q[row] = col;
for(int i = 0; i < row; i++)
if(q[i] - q[row] == i - row ||
q[i] - q[row] == row - i)
return 0;
return 1;
}
void queen8(int row){
if(row == 8){
printQ();
return ;
}
static int book[8] = {};
for(int j = 0; j < 8; j++)
if(book[j] == 0 && check(row, j)){
book[j] = 1;
queen8(row + 1);
book[j] = 0;
}
}
int main(){
queen8(0);
return 0;
}
//八皇后-回溯法迭代实现(强哥写的)
#include <stdio.h>
int q[8] = {0};
int check(int count){
int i;
for(i=0; i<count; i++)
if(q[i]==q[count] || q[i]-q[count]==i-count
|| q[i]-q[count]==count-i) return 0;
return 1;
}
void printQ(){
static int count=1;
printf("%d : ",count);
int i;
for(i=0; i<8; i++) printf("%d,",q[i]);
putchar('\n');
// getchar();
count++;
}
void queen8i(){
int count = 0;
q[0] = -1;
while(count>=0){
q[count]++;
if(q[count]==8){
count--;
continue;
}
if(check(count)){
if(count<7){
count++;
q[count] = -1;
}else{
printQ();
count--;
}
}
}
}
void main(){
queen8i();
}
//八皇后-回溯法迭代实现(自己写的)
#include <stdio.h>
int q[8] = {0};
int check(int count){
int i;
for(i=0; i<count; i++)
if(q[i]==q[count] || q[i]-q[count]==i-count
|| q[i]-q[count]==count-i) return 0;
return 1;
}
void printQ(){
static int count=1;
printf("%d : ",count);
int i;
for(i=0; i<8; i++) printf("%d,",q[i]);
putchar('\n');
// getchar();
count++;
}
void queen8i()
{
int count=0;
q[0]=-1;
while(count>=0)
{
if(q[count]<7)
q[count]++;
else
{
count--;
continue;
}
if(check(count))
{
if(count==7)
printQ();
else{
count++;
q[count]=-1;
}
}
}
}
void main(){
queen8i();
}