LeetCode No.52 N-Queens II

Follow up for N-Queens problem.

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

===================================================================

題目鏈接:https://leetcode.com/problems/n-queens-ii/

題目大意:N皇后問題,求出滿足N皇后的解法個數。

思路:深度搜索,寬度搜索或者回溯。

參考代碼:

class Solution {
public:
    int totalNQueens(int n) {
        int ans = 0 ;
        if ( n <= 1 )
            return 1 ;
        for ( int i = 0 ; i < n ; i ++ )
        {
            vector < pair <int,int> > v ;
            v.push_back ( make_pair ( 0 , i ) ) ;
            queue < vector < pair <int,int> > > q ;
            q.push ( v ) ;
            while ( ! q.empty() )
            {
                v = q.front() ;
                q.pop() ;
                int index = v.back().first + 1 ;
                for ( int j = 0 ; j < n ; j ++ )
                {
                    if ( isValid ( n , v , index , j ) ) 
                    {
                        vector < pair <int,int> > temp = v ;
                        temp.push_back ( make_pair ( index , j ) ) ;
                        if ( index == n - 1 )
                            ans ++ ;
                        else
                            q.push ( temp ) ;
                    }
                }
            }
        }
        return ans ;
    }
private :
    bool isValid ( int n , const vector < pair <int,int> >& v , int x , int y )
    {
        for ( int i = 0 ; i < v.size() ; i ++ )
        {
            if ( x == v[i].first || y == v[i].second || x - v[i].first == y - v[i].second || x - v[i].first == v[i].second - y )
                return false ;
        }
        return true ;
    }
};




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章