第八章 数组 -- 八皇后问题


问题描述:

皇后是国际象棋中威力最大的棋子。在下面所示的棋盘中,皇后可以攻击位于箭头索覆盖位置的所有棋子。


                            

我们能不能把8个皇后放在棋盘上,它们中的任何一个都无法攻击其余的皇后? 我们把这个问题成为八皇后问题。编写一个程序,找到八皇后问题的所有答案。


/*
** Solve the Eight Queens Problem.
*/
#include <stdio.h>
#include <stdlib.h>

#define TRUE  1
#define FALSE 0

/*
** The chessboard. If an element is TRUE, there is a queen on that square;
** if FALSE, no queen.
*/
int board[8][8];

/*
** print_board
**
** Print out a valid solution.
*/
void print_board(void)
{
	int row;
	int column;
	static int n_solutions;
	
	n_solutions += 1;
	printf( "Solution #%d:\n", n_solutions );
	
	for( row = 0; row < 8; row += 1 )
    {
		for( column = 0; column < 8; column += 1 )
	    {
			if( board[ row ][ column ] )
			    printf( " Q" );
			else
                printf( " +" );
        }
        putchar( '\n' );
     }
     
     putchar( '\n');
}
/*
** conflicts
**
** Check the board for conflicts with the queen that was just placed.
** NOTE: because the queens are placed in the rows in order, there is no
** need to look at rows below the current one as there are no queens there!
*/
int conflicts( int row, int column )
{
	int i;
	
	for( i = 1; i < 8; i += 1 )
	{
		/*
		** Check up, left, and right. (Don’t have to check down; no
		** queens in those rows yet!)
		*/
	
		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. (Don’t have
		** to check down; no queens there yet!)
		*/
		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;
	}
	/*
	** If we get this far, there were no conflicts!
	*/
	return FALSE;
}

/*
** place_queen
**
** Try to place a queen in each column of the given row.
*/
void place_queen( int row )
{
	int column;
	/*
	** Try each column, one by one.
	*/
	for( column = 0; column < 8; column += 1 )
	{
		board[ row ][ column ] = TRUE;
		/*
		** See if this queen can attack any of the others (don’t need to
		** check this for the first queen!).
		*/
		if( row == 0 || !conflicts( row, column ) )
			/*
			** No conflicts –– if we’re not yet done, place the next
			** queen recursively. If done, print the solution!
			*/
			if( row < 7 )
				place_queen( row + 1 );
			else
				print_board();
			
		/*
		** Remove the queen from this position.
		*/
		board[ row ][ column ] = FALSE;
	}
}

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

摘自《c 和指针》


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值