using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EightQueenRecursive
{
class Program
{
//定义棋盘
int[] a = new int[8];
//定义解决方案个数
int solution=0;
//规则
public bool isOK(int row,int col)
{
for(int i = 0; i < row; i++)
{
if (a[i] == col||Math.Abs(a[i]-col)==Math.Abs(i-row))
{
return false;
}
}
return true;
}
//显示
void display()
{
Console.WriteLine("第{0}种解", solution++);
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 8; j++)
{
if (a[i] == j)
{
Console.Write("Q");
}else
{
Console.Write("#");
}
}
Console.WriteLine();
}
Console.WriteLine("--------");
}
void DSF(int row)
{
//find
for (int i = 0; i < 8; i++)
{
if (isOK(row,i))
{
a[row] = i;
if (row<7)
{
//forward
DSF(row + 1);
}
else
{
//done
display();
}
}
else
{
}
}
//back
}
static void Main(string[] args)
{
Program p = new Program();
//初始化棋盘
foreach(int i in p.a)
{
p.a[i] = 0;
}
p.DSF(0);
Console.ReadKey();
}
}
}
用DFS解决八皇后问题(递归)(c#)
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 需要注意的是,比如如下代码: 为什么不是直接 stackk.Push(node);不是更方便吗由于本人知识浅薄,还...