using System;
using System.Collections;
namespace Agro
{
/// <summary>
/// NKing 的摘要说明。
/// </summary>
public class NKing
{
public int N=0;//N后
public ArrayList result=new ArrayList();//表示解
private int [] xx;//当前解表示 xx[t]=i表示第T行第I列有皇后
public NKing(int n)//n表示n个皇后
{
this.N=n;
xx=new int[N+1];
for(int i=1;i<xx.Length;i++)
xx[i]=0;
BackTrack(1);
}
private void BackTrack(int t )
{
if(t>N)//到了最后一行
{
Array temp=Array.CreateInstance(System.Type.GetType("System.Int32"),N+1);
xx.CopyTo(temp,0);
result.Add(temp);
return;
}
//else
for(int i=1;i<=this.N;i++)
{
xx[t]=i;
if(this.isOK(t))BackTrack(t+1);
}
}
private bool isOK(int k)
{
for (int j=1;j<k;j++)
if((Math.Abs(k-j)==Math.Abs(xx[j]-xx[k]))||(xx[j]==xx[k]))return false;
return true;
}
}
}
此博客使用C#语言解决N皇后问题。定义了NKing类,在构造函数中初始化皇后数量和当前解数组,调用BackTrack方法进行回溯求解。BackTrack方法递归寻找解,isOK方法用于判断皇后放置是否合法,最终将解存储在ArrayList中。
395

被折叠的 条评论
为什么被折叠?



