八皇后问题 回溯法

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Text;
 5 using System.Threading.Tasks;
 6 
 7 namespace Demo
 8 {
 9     class Program
10     {
11         static int num = 8;/*可以随意修改,num是多少解的就是几皇后问题*/
12         static int[] arr = new int[8];
13         static int count = 0;
14         static void display()/*一个简单的数组输出函数,顺便统计解的个数*/
15         {
16             for (int i = 0; i < num; ++i)
17             {
18                 for (int j = 0; j < num; j++)
19                 {
20                     if (arr[i] == j)
21                         Console.Write("Q");
22                     else
23                         Console.Write("*");
24                 }
25 
26                 Console.WriteLine(" ");
27             }
28             count++;
29             Console.WriteLine("-------------" + count.ToString() + "--------------------");
30         }
31 
32         static void queens(int pos = 0)
33         {
34             /*同在斜线或者直线上*/
35             for (int i = 0; i < pos-1; ++i)
36              {
37                 int off = arr[i] - arr[pos - 1];
38                 if (off == 0 || off == pos - 1 - i || -off == pos - 1 - i)
39                     return;
40             }
41 
42             /*符合条件就输出*/
43             if (pos == num)
44             { 
45                 display(); 
46                 return; 
47             }
48 
49             /*递归搜索解空间*/
50             for (int k = 0; k < num; ++k)
51             {
52                 arr[pos] = k;
53                 queens(pos + 1);
54             }
55         }
56 
57         static void Main(string[] args)
58         {
59             queens(0);
60 
61             Console.ReadKey();
62 
63         }
64     }
65 }

 

posted on 2015-01-05 18:12  绝处而逢生  阅读(635)  评论(0编辑  收藏  举报

导航