using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SeqListSort { /// <summary> /// 8皇后算法 /// <ather> /// <lihonglin> /// </ather> /// </summary> class EightQueen { private const int COL = 8;// 行 private const int ROW = 8; private static int[,] map = new int[COL, ROW];// 棋盘 private static int Count = 0;// 摆放皇后位置的种数 // 放置皇后 public static void PutQueen(int row) { int i = 0; if (ROW == row)//结束条件 { Display(); return; } // 一列一列摆放 for (i = 0; i < COL; ++i ) { if (IsOK(row, i)) { map[row, i] = 8; PutQueen(row+1); // 回溯 map[row, i] = 0; } } } // 摆放规则 public static bool IsOK(int x, int y) { for (int i = 0; i < COL; i++) { for (int j = 0; j < ROW; ++j) { //摆放规则,同一行,同一列,该位置的斜边和逆斜边都不能放 if (i == x || j == y || (x + y == i + j) || ( x - y == i - j)) { if (8 == map[i,j]) { return false; } } } } return true; } public static void Display() { Count++; Console.WriteLine (" 第{0}种 " , Count); for (int i = 0; i < COL; i++) { for (int j = 0; j < ROW; ++j) { Console.Write( " "+ map[i,j] ); } Console.WriteLine(); } } } }