八皇后问题—C语言

#include <stdio.h>
#include <stdlib.h>

#define TRUE 1
#define FALSE 0

int board[8][8];

void print_board(){
int row;
int column;

static int n_solutions;

n_solutions+=1;

printf("Solution #%d: \n",n_solutions);

for (row=0;row<8;row++)
{
for (column=0;column<8;column++)
{
if (board[row][column])
printf("%3c",'Q');
else
printf("%3c",'+');
}
putchar('\n');
}
putchar('\n');
}

int conficts(int row,int column){
int i;

for (i=1;i<8;i++)
{
/************************************************************************/
/* Check up,left,right don't have to check down! */
/************************************************************************/
if(row-i>=0&&board[row-i][column])
return TRUE;
if(column-i>=0&&board[row][column-i])
return TRUE;
if(column+i<8&&board[row][column+i])
return TRUE;
/************************************************************************/
/* Check the diagonals:up and left,up and right */
/************************************************************************/
if(row-i>=0&&column-i>=0&&board[row-i][column-i])
return TRUE;
if(row-i>=0&&column+i<8&&board[row-i][column+i])
return TRUE;
}

return FALSE;
}

void place_queen(int row){
int column;

for (column=0;column<8;column++)
{
board[row][column]=TRUE;

if (row==0||!conficts(row,column))
{
if (row<7)
place_queen(row+1);
else
print_board();
}
board[row][column]=FALSE;
}
}

int main(){
place_queen(0);
return EXIT_SUCCESS;
}

你可能感兴趣的:(C语言)