C#递归求解八皇后

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

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; } } }

你可能感兴趣的:(String,C#,Class)