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 ;
}
};