随笔 - 149  文章 - 8  评论 - 248  阅读 - 21万

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;
}

posted on   几度夕阳红了  阅读(364)  评论(0编辑  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· .NET周刊【3月第1期 2025-03-02】
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· [AI/GPT/综述] AI Agent的设计模式综述
< 2010年10月 >
26 27 28 29 30 1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31 1 2 3 4 5 6

点击右上角即可分享
微信分享提示