八皇后问题递归c语言,一个八皇后问题的递归实现(C)

OS:FC3

Compiler: gcc version 3.4.2

#include #include

#define RANK 8

char board[RANK][RANK];

int check_up(int row, int column)

{

int i = row -1;

//      printf("check_up, %d, %d\n", row, column);

while(i >= 0)

{

if(board[i][column] == 'Q')

return 0;

i --;

}

return 1;

}

int check_up_left(int row, int column)

{

int i = row - 1, j = column - 1;

//      printf("check_up_left, %d, %d\n", row, column);

while(i >= 0 && j >= 0)

{

if(board[i][j] == 'Q')

return 0;

i --;

j --;

}

return 1;

}

int check_up_right(int row, int column)

{

int i = row - 1, j = column + 1;

//      printf("check_right, %d, %d\n", row, column);

while(i >= 0 && j <= 7)

{

if(board[i][j] == 'Q')

return 0;

i --;

j ++;

}

return 1;

}

int check(int row, int column)

{

int res = 0;;

//      printf("check %d, %d\n", row, column);

if(row == 0)

return 1;

switch(column)

{

case 0:

res = (check_up(row,column)) && (check_up_right(row,column));

break;

case (RANK-1):

res = (check_up(row, column)) && (check_up_left(row,column));

break;

default:

res = (check_up(row, column)) && (check_up_left(row,column)) && (check_up_right(row,column));

break;

}

return res;

}

void show()

{

int i, j;

printf(" ");

for(i = 0; i < RANK; i ++)

printf("\33[4m  \33[0m");

printf("\n");

for(i = 0; i < RANK; i ++)

{

printf("|");

for(j  = 0; j < RANK ; j ++)

printf("\33[4m%c|", board[i][j]);

printf("\33[0m\n");

}

printf("\n");

}

void init_board()

{

int i, j;

for(i = 0; i < RANK; i ++)

for(j  = 0; j < RANK ; j ++)

board[i][j] = ' ';

}

void empress(int row)

{

int i, j, k;

sleep(1);

if(row == RANK -1) //last row

{

for(i = 0; i < RANK; i ++)

{

if(check(row, i))

{

board[row][i] = 'Q';

show();

}

board[row][i] = ' ';

}

return ;

}

for(i = 0; i < RANK; i ++)

{

if(check(row, i))

{

for(k = row; k < RANK ; k ++)

for(j = 0; j < RANK ; j ++)

board[k][j] = ' ';

board[row][i] = 'Q';

empress(row+1);

}

}

}

int main()

{

init_board();

empress(0);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值