1. 程式人生 > >N皇后II

N皇后II

n 皇后問題研究的是如何將 n 個皇后放置在 n×n 的棋盤上,並且使皇后彼此之間不能相互攻擊。

在這裡插入圖片描述

上圖為 8 皇后問題的一種解法。

給定一個整數 n,返回 n 皇后不同的解決方案的數量。

在這裡插入圖片描述

感覺N皇后II是皇后I的簡單版啊,哈哈。

bool isok(int row,int a[]){
    for(int i=0;i<row;i++)
      if(a[i]==a[row]||fabs(a[row]-a[i])==row-i)
      return false;
  return true;
}
void queen(int row,int n,int a[],int& total){
    if(row==n)
    ++total;
    else
    for(int col=0;col!=n;col++){
     a[row]=col;
     if(isok(row,a))
     queen(row+1,n,a,total);
    }  
}
class Solution {
public:
    int totalNQueens(int n) {
        int a[n],total=0;
       queen(0,n,a,total);
       return total;
    }
};

程式碼如有錯誤,歡迎大家指出!