8皇后和N皇后问题
The eight queens puzzle is the problem of placing eight chess queens on an 8×8 chessboard such that none of them are able to capture any other using the standard chess queen's moves. The queens must be placed in such a way that no two queens attack each other. Thus, a solution requires that no two queens share the same row, column, or diagonal. The eight queens puzzle is an example of the more general n-queens problem of placing n queens on an n×n chessboard, where solutions exist only for n = 1 or n ≥ 4.

History
The puzzle was originally proposed in 1848 by the chess player Max Bezzel, and over the years, many mathematicians, including Gauss, have worked on this puzzle and its generalized n-queens problem. The first solutions were provided by Franz Nauck in 1850. Nauck also extended the puzzle to n-queens problem (on an n×n board—a chessboard of arbitrary size). In 1874, S. Günther proposed a method of finding solutions by using determinants, and J.W.L. Glaisher refined this approach.
Edsger Dijkstra used this problem in 1972 to illustrate the power of what he called structured programming. He published a highly detailed description of the development of a depth-first backtracking algorithm.2
Below is one solution for 8 or N queen puzzle using C language description,you can define the value of N.
#include "stdafx.h"
#include <stdio.h>
#include <conio.h>
#include <math.h>
int k=1;
int count=0; //共有多少种摆法
#define N 8
int queen[N]; //N个皇后的列的坐标
void Queen();
void PrintQueen(); //输出当前N个皇后的位置
bool CheckSafe(); //检查当前已经放置的皇后的位置是否安全
void main()
{
Queen();
printf("共有%d种摆法",count);
getchar();
}
void Queen()
{
if(k>N) //N个皇后的放置都安全,则输出此时的放置顺序
{
PrintQueen();
count++;
}
else
{
for(int i=1;i<=N;i++)
{
queen[k-1]=i; //将第K个皇后放在i位置上
if(CheckSafe())
{
//如果已经放置的几个皇后都安全,则放置下一个皇后
k++;
Queen();
}
}
}
k--; //回溯到上一个皇后的位置
}
void PrintQueen()
{
for(int i=1;i<=N;i++)
{
printf("第%d个皇后的位置为:%d\n",i,queen[i-1]);
}
printf("\n");
}
bool CheckSafe()
{
for(int i=0;i<k-1;i++)
{
if(queen[k-1]==queen[i]) //两个皇后在同一列上
return false;
if(((queen[k-1]-queen[i])==(k-1-i))||((queen[k-1]-queen[i])==-(k-1-i))) //两个皇后在一条斜线上
return false;
}
return true;
}
浙公网安备 33010602011771号