/*
*Copyright (c) 2016, 烟台大学计算机学院
*All rights reserved.
*文件名称:main.cpp
*作者:张旺华
*完成日期: 2016 年 7 月 2 日
*版本号:v1.0
*问题描述:编写一个求n皇后问题
*
*/
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
int cont=0; //记录解个数
typedef struct
{
int col[MaxSize]; //col[i]存放第i个皇后的列号
int top; //栈顶指针
} StType; //定义顺序栈类型
int count=0;
bool place(StType st,int i,int j) //测试(i,j)是否与1~i-1皇后有冲突
{
int k=1;
if (i==1) return true; //放第一个皇后时没有冲突
while (k<=i-1) //j=1到k-1是已放置了皇后的列
{
if ((st.col[k]==j)
|| (abs(j-st.col[k])==abs(k-i)))
return false;
k++;
}
return true;
}
void queen(int n) //求解n皇后问题
{
int i,j,k;
bool find;
StType st; //定义栈st
st.top=0; //初始化栈顶指针
st.top++; //将(1,1)进栈
st.col[st.top]=1;
while (st.top>0) //栈不空时循环
{
i=st.top; //当前皇后为第i个皇后
if (st.top==n) //所有皇后均放好,输出一个解
{
求解N皇后问题
最新推荐文章于 2023-04-25 21:00:32 发布