C#用递归算法解决八皇后问题

2019-12-30 12:55:53刘景俊

总结一下,用回溯的方法解决8皇后问题的步骤为:

1)从第一列开始,为皇后找到安全位置,然后跳到下一列

2)如果在第n列出现死胡同,如果该列为第一列,棋局失败,否则后退到上一列,在进行回溯

3)如果在第8列上找到了安全位置,则棋局成功。

8个皇后都找到了安全位置代表棋局的成功,用一个长度为8的整数数组queenList代表成功摆放的8个皇后,数组索引代表棋盘的col向量,而数组的值为棋盘的row向

量,所以(row,col)的皇后可以表示为(queenList[col],col),如上图中的几个皇后可表示为:

queenList[0] = 0;  queenList[1] = 3;   queenList[2] = 1;  queenList[3] = 4;   queenList = 2;

我们看一下如何设计程序:

首先判断(row,col)是否是安全位置的算法:


bool IsSafe(int col,int row,int[] queenList)
{
 //只检查前面的列
 for (int tempCol = 0; tempCol < col; tempCol++)
 {
  int tempRow = queenList[tempCol];
  if (tempRow == row)
  {
   //同一行
   return false;
  }
  if (tempCol == col)
  {
   //同一列
   return false;
  }
  if (tempRow - tempCol == row - col || tempRow + tempCol == row + col)
  {
   return false;
  }
 }
 return true;
}

设定一个函数,用于查找col列后的皇后摆放方法:


/// <summary>
/// 在第col列寻找安全的row值
/// </summary>
/// <param name="queenList"></param>
/// <param name="col"></param>
/// <returns></returns>
public bool PlaceQueue(int[] queenList, int col)
{
 int row = 0;
 bool foundSafePos = false;
 if (col == 8) //结束标志
 {
  //当处理完第8列的完成
  foundSafePos = true;
 }
 else
 {
  while (row < 8 && !foundSafePos)
  {
   if (IsSafe(col, row, queenList))
   {
    //找到安全位置
    queenList[col] = row;
    //找下一列的安全位置
    foundSafePos = PlaceQueue(queenList, col + 1);
    if (!foundSafePos)
    {
     row++;
    }
   }
   else
   {
    row++;
   }
  }
 }
 return foundSafePos;
}

调用方法:


static void Main(string[] args)
{
 EightQueen eq = new EightQueen();
 int[] queenList = new int[8];
 for (int j = 0; j < 8; j++)
 {
  Console.WriteLine("-----------------"+j+"---------------------");
  queenList[0] = j;
  bool res = eq.PlaceQueue(queenList, 1);

  if (res)
  {
   Console.Write(" ");  
   for (int i = 0; i < 8; i++)
   {
    Console.Write(" " + i.ToString() + " ");  
   }
   Console.WriteLine("");
   for (int i = 0; i < 8; i++)
   {
    Console.Write(" "+i.ToString()+" ");      
    for (int a = 0; a < 8; a++)
    {       
     if (i == queenList[a])
     {
      Console.Write(" q ");
     }
     else
     {
      Console.Write(" * ");
     }
    }
    Console.WriteLine("");
      
   }
   
   Console.WriteLine("---------------------------------------");
  }
  else
  {
   Console.WriteLine("不能完成棋局,棋局失败!");
  }
 }
 Console.Read();
}