1 /* 2 n-皇后问题: 3 n皇后问题等于在n*n格的棋盘上防止彼此不受攻击的n个皇后,按照国际象棋的规则,皇后可以攻击与之 4 处在同一行或同一列或同一斜线上的棋子,求解可以放置的方法种数。 5 */ 6 private static int count = 0; 7 static void Main(string[] args) 8 { 9 while (true) 10 { 11 Console.WriteLine("请输入大于3的数,将会显示所有满足皇后问题的解..."); 12 int n = Convert.ToInt32(Console.ReadLine()); 13 List<int> queens = new List<int>(); 14 for (int i = 0; i < n; i++) 15 { 16 queens.Add(0); 17 } 18 Console.WriteLine("{0}-皇后问题的解:",n); 19 PutQueens(queens, 0); 20 } 21 } 22 /// <summary> 23 /// 安排皇后位置是判断是否会相互攻击 24 /// </summary> 25 /// <param name="queens">皇后列表</param> 26 /// <param name="current">当前皇后索引</param> 27 /// <returns></returns> 28 private static bool IsMatch(List<int> queens, int current) 29 { 30 for (int i = 0; i < current; i++) 31 { 32 if (queens[i] == queens[current] || Math.Abs(queens[i] - queens[current]) == Math.Abs(i - current)) 33 { 34 return false; 35 } 36 } 37 return true; 38 } 39 /// <summary> 40 /// 放皇后 41 /// </summary> 42 /// <param name="queens">皇后列表</param> 43 /// <param name="current">当前皇后索引</param> 44 private static void PutQueens(List<int> queens,int current) 45 { 46 int n = queens.Count; 47 for (queens[current] = 1; queens[current] <= n;queens[current]++ ) 48 { 49 if (IsMatch(queens, current)) 50 { 51 //当前位置满足情况,不会被攻击,换下一个皇后进场 52 current++; 53 if (current < n) 54 { 55 PutQueens(queens, current); 56 } 57 else 58 { 59 count++; 60 Console.WriteLine("第{0}中方法:",count); 61 for (int i = 0; i < queens.Count; i++) 62 { 63 Console.Write(queens[i].ToString()+" "); 64 } 65 Console.WriteLine(); 66 } 67 //递归结束后current--,退出所有的递归current又变成0,进行下一轮 68 current--; 69 } 70 } 71 }