用栈求解n皇后问题

问题描述:
编写一个程序求解n皇后问题,即在m×n的方格棋盘上放置n个皇后,要求每个皇后不同行、不同列、不同左右对角线,下图是八皇后问题的一个解。(1)皇后个数n由用户输入,其值不能超过20,输出所有的解。(2)采用类似于用栈求解迷宫问题的方法。

在这里插入图片描述

代码展示:

#include <stdio.h>
#include <stdlib.h>
#define MaxSize 100
typedef struct
{	int col[MaxSize];				
	int top;						
} StackType;						
void dispasolution(StackType St)   		
{	static int count=0;				
	printf("  第%d个解:",++count);
	for (int i=1;i<=St.top;i++)
		printf("(%d,%d) ",i,St.col[i]);
	printf("\n");
}
bool place(StackType St,int k,int j)
{	int i=1;
	if (k==1) return true;				
	while (i<=k-1)					
	{	if ((St.col[i]==j) || (abs(j-St.col[i])==abs(i-k)))
			return false;			
		i++;
	}
	return true;						
}
void queen(int n)					
{
	int k;
	bool find;
	StackType St;						
	St.top=0;						
	St.top++; St.col[St.top]=0;			
	while (St.top!=0)				
	{	k=St.top;					
		find=false;						
		for (int j=St.col[k]+1;j<=n;j++)
			if (place(St,k,j))			
			{	St.col[St.top]=j;	
				find=true;				
				break;				
			}
		if (find)					
		{	if (k==n)				
				dispasolution(St);
			else						
			{	St.top++;
				St.col[St.top]=0;	
			}
		}
		else						
			St.top--;				
	}
}
int main()
{	int n;							
	printf("皇后问题(n<20) n=");
	scanf("%d",&n);
	if (n>20)
		printf("n值太大\n");
	else
	{	printf(" %d皇后问题求解如下:\n",n);
		queen(n);
	}
	return 1;
}

运行结果:
在这里插入图片描述
(截取最后部分)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值