n皇后問題

N-Queens:來自leetcode

Follow up for N-Queens problem.

Now, instead outputting board configurations, return the total number of distinct solutions.

計算機n皇后問題的不同放法:



class Solution {
public:

    int num;
    int ans;

    //由於每行只放一個元素,故不需要檢查行,只需檢查列和對角線即可
    bool isValid(vector<int> &cols, int row, int col){
        for(int i=0; i<row; i++){
            int colum=cols[i];
            
            //如果在該列上已經有皇后了,則是非法
            if(col==colum)
                return false;
            
            //檢查對角線,這裏只需要分別計算行標的差值與列標的差值,看是否相等即可
            int disRaw=row-i;
            int disCol=abs(col-colum);
            if(disRaw==disCol)
                return false;
        }
        return true;
    }

    //cols存放每行中的皇后所在的列
    void placeQuee(vector<int> &cols, int row){
        if(row==num){//找到有效的解法
            ans++;
            return;
        }
        for(int i=0; i<num; i++){//每次一行只放一個皇后
            if(isValid(cols, row, i)){//檢查在該位置是否合法
                cols[row]=i;
                placeQuee(cols, row+1);
            }
        }
    }

    int totalNQueens(int n) {
        vector<int> tmp(n);
        ans=0;
        num=n;
        placeQuee(tmp, 0);
        return ans;
    }
};



發佈了90 篇原創文章 · 獲贊 17 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章