非递归形式的N皇后问题---用C#实现,VS2008可以执行

        补充一下,解决8皇后需要不到一秒时间,16皇后需要大约4分钟。32皇后我测试了8天,这8天基本上没用电脑,回朔搜索到了217亿次,后来没有耐心等下去了,结束了程序,没有搜索到结果。

 

using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Queue { class Program { static void Main(string[] args) { DateTime start = DateTime.Now ; //定义N皇后问题的值,可以改变 const int N = 32; //存储搜索路径 List<MetrixElemnet> list = new List<MetrixElemnet>(); //回溯搜索次数 long loop = 0; //矩阵行 int i = 0; //矩阵列 int j = 0; while (true) { while (i < N) { while (j < N) { MetrixElemnet m = new MetrixElemnet(); m.row = i; m.col = j; if (Check(list, m) == 1) { list.Add(m); break; } else { j++; } } i++; j = 0; } loop++; if (list.Count == N) { Console.WriteLine("Loop {0}", loop); PrintElement(list); DateTime end = DateTime.Now; TimeSpan span = end - start; Console.Write("Eclipse {0} MS",span.Minutes); Console.ReadLine(); break; } else { if (loop % 600 == 0) { Console.Write("Loop {0}", loop); Console.CursorLeft = 0; } // PrintElement(list); if (list.Count >= 2) { MetrixElemnet m = list[list.Count -1]; i = m.row; j = m.col + 1; list.RemoveAt(list.Count -1); } else if (list.Count == 1) { MetrixElemnet m = list[list.Count - 1]; i = m.row; j++; list.RemoveAt(list.Count - 1); } } } } /// <summary> /// 输出当前矩阵元素 /// </summary> /// <param name="list"></param> private static void PrintElement(List<MetrixElemnet> list) { if ((list != null) && (list.Count >= 1)) { foreach (MetrixElemnet m in list) { Console.Write("[{0},{1}]",m.row+1 ,m.col+1); } Console.WriteLine(); } else { // Console.WriteLine("Empty"); } } /// <summary> /// 检查当前矩阵值是否符合要求 /// </summary> /// <param name="list"></param> /// <param name="element"></param> /// <returns></returns> private static int Check( List<MetrixElemnet> list, MetrixElemnet element ) { if (list.Count >= 1) { int tmp = list.Count; for (int i = 0; i < list.Count; i++) { if (list[i].row == element.row) { tmp--; } else if (list[i].col == element.col) { tmp--; } else if (Math.Abs(list[i].row - element.row) == Math.Abs(list[i].col - element.col)) { tmp--; } } if (tmp == list.Count) { return 1; } else { return 0; } } else if (list.Count == 0) { return 1; } else { return 0; } } } /// <summary> /// 矩阵元素数据结构 /// </summary> struct MetrixElemnet { public int row; public int col; } }

你可能感兴趣的:(eclipse,数据结构,struct,String,list,C#)