八皇后问题

控制台显示八皇后:

1 class Queens
2 {
3 const int QueenCount = 8;//皇后数目。
4 static int[] QueenPositions = new int[QueenCount];//每行放置皇后的位置。
5 static int total = 0;//放置方案的数目。
6
7 static void Main(string[] args)
8 {
9 Place(0);
10 }
11
12 /// <summary>
13 /// 在第row行上放置一个皇后。
14 /// </summary>
15 /// <param name="row">放置皇后的行row。</param>
16 static void Place(int row)//在第row行上放置一个皇后。
17 {
18 if (row >= QueenCount)
19 {
20 total++;//此时找到了一种放置方案。
21 Print();
22 return;
23 }
24
25 for (int col = 0; col < QueenCount; col++)//在第row行上尝试每一个位置。
26 {
27 bool attack = false;
28 for (int iRow = 0; iRow < row; iRow++)
29 {
30 if (QueenPositions[iRow] == col || Math.Abs(iRow - row) == Math.Abs(QueenPositions[iRow] - col))
31 {
32 attack = true;
33 break;
34 }
35 }
36 if (!attack)
37 {
38 QueenPositions[row] = col;
39 Place(row + 1);
40 }
41
42 }
43 }
44
45 /// <summary>
46 /// 打印输出
47 /// </summary>
48 static void Print()
49 {
50 System.Console.Write("{0}:", total);
51 foreach (var item in QueenPositions)
52 {
53 System.Console.Write("{0} ", item);
54 }
55 System.Console.WriteLine();
56 }
57 }
posted @ 2011-02-12 09:55  liumeibiao  阅读(245)  评论(0编辑  收藏  举报