C#递归求解八皇后

王朝学院·作者佚名  2009-02-05  
宽屏版  字体: |||超大  

C#递归求解八皇后,废话不说了,直接看代码吧。

view plaincopy to clipboardprint?

using System;

using System.Collections.Generic;

using System.Text;

namespace Queen

{

/*

* 八皇后问题

* @Author: Red_angelX

*/

class Program

{

const int NCOUNT = 8;

static int[] QueenMap = new int[NCOUNT];

static int iCount = 1;

static void Main(string[] args)

{

int current = System.Environment.TickCount;

PlayQueen(0);

Console.WriteLine("Eclped {0} ms", Environment.TickCount - current);

Console.Read();

}

/*

* 核心函数,放置第N枚皇后(递归)

*/

static void PlayQueen(int n)

{

if (n == NCOUNT)

{

PrintResult();

return;

}

for (int i = 1; i <= NCOUNT; i++)

{

QueenMap[n] = i;

if (IsValid(n))

PlayQueen(n + 1);

}

}

/*

* 输出结果

*/

static void PrintResult()

{

Console.Write("No.{0} ", iCount++);

for (int i = 0; i < NCOUNT; i++)

Console.Write("{0} ", QueenMap[i]);

Console.Write(" ");

}

/*

* 检查第n个皇后放上去之后是否合法

*/

static bool IsValid(int n)

{

for (int i = 0; i < n; i++)

{

if (QueenMap[i] == QueenMap[n])

return false;

if (Math.Abs(QueenMap[i] - QueenMap[n]) == n - i)

return false;

}

return true;

}

}

}

http://blog.csdn.net/gisfarmer/archive/2009/02/03/3860266.aspx

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
© 2005- 王朝网络 版权所有