Learning algorithm: Eight Queens problem (backtracking)

In chess, the queen may not be limited to the number of steps to eat other pieces in the horizontal, vertical and diagonal lines. How eight queens on the chessboard (8x8 squares), so that they can not be eaten by anyone! This is the famous eight queens problem.
Known 8 queens problem set a total of 92 solutions, i.e. 92 different strings Queen

Backtracking: also known as "heuristics." When solving problems, not a one-step, try holding the attitude is, if we find the current selection achieving its purpose or not optimal, then immediately make a withdrawal operation.

Backtracking and recursion:
Recursion: you are very clear what to do (how to walk every step you are well aware)
back: somewhat similar to brute-force method, all the circumstances to try again, if you continue to go down the line, if not to go back down . Backtracking can be achieved when using recursive

Ideas: 1, starting from the zero-th row, the first row 0 column 0 placing a queen, a queen in turn placed in a position in the first row to the seventh row, which determines whether the placement position queen, if not, then in this position the rear position and then try to put a queen, if you can then place a queen in this position, and then the next line to try, if the row all positions not possible, then back to the line, changes queen on one row position, continue to try to down
2, if you try to the last line and the last line position can put the Queen, then our objective was achieved.
3. If the attempt is successful then use the same method to continue to try other different pendulum method.

//两个全局变量
int board[8][8] = {0};	//棋盘
int sum = 0;		//计数器

//如果可以摆放皇后则返回 1,否则返回 0
int check(int row, int col)	//判断(row, col)位置是否可以摆放皇后
{
	int i, j;
	//判断第col列有没有皇后
	for(i = 0; i < 8; i++)
	{
		if( 1 == board[i][col] )
			return 0;
	}
	//判断左上对角线有没有皇后
	for(i = row, j = col; i >= 0 && j >= 0; i--, j--)
	{
		if( 1 == board[i][j] )
			return 0;
	}
	//判断右上对角线有没有皇后
	for(i = row, j = col; i >= 0 && j < 8; i--, j++)
	{
		if( 1 == board[i][j] )
			return 0;
	}
	return 1;
}
//放皇后
void put_queen(int row)
{
	if(8 == row)	//递归结束条件
	{
		sum++;	//找到一种解法,计数器++
		return;
	}
	int i;
	for(i = 0; i < 8; i++)
	{
		if( check(row, i) )
		{
			board[row][i] = 1;	//放下皇后
			put_queen(row + 1);	//递归
			board[row][i] = 0;	//回溯前把之前的皇后标记清零
		}
	}
}

int main(void)
{	
	put_queen(0);	//从第0行开始放皇后
	printf("总共有 %d 种摆法\n", sum);		//总共有92种摆法
	
	return 0;
}
Published 50 original articles · won praise 5 · Views 1532

Guess you like

Origin blog.csdn.net/qq_42483691/article/details/104580545