标签:style blog http color io for ar div log
Follow up for N-Queens problem.
Now, instead outputting board configurations, return the total number of distinct solutions.
思路:穷举所有合法的摆法。
1 class Solution { 2 public: 3 int totalNQueens( int n ) { 4 solutions = 0; 5 vector<string> solution( n, string( n, ‘.‘ ) ); 6 SolveSub( solution, 0, n ); 7 return solutions; 8 } 9 private: 10 void SolveSub( vector<string>& solution, int step, const int &n ) { 11 if( step == n ) { ++solutions; return; } 12 for( int i = 0; i < n; ++i ) { 13 bool used = false; 14 for( int k = step-1; k >= 0; --k ) { 15 if( solution[k][i] == ‘Q‘ ) { used = true; break; } 16 } 17 if( used ) { continue; } 18 for( int k = 1; k <= min( i, step ); ++k ) { 19 if( solution[step-k][i-k] == ‘Q‘ ) { used = true; break; } 20 } 21 if( used ) { continue; } 22 for( int k = 1; k <= min( n-i, step ); ++k ) { 23 if( solution[step-k][i+k] == ‘Q‘ ) { used = true; break; } 24 } 25 if( used ) { continue; } 26 solution[step][i] = ‘Q‘; 27 SolveSub( solution, step+1, n ); 28 solution[step][i] = ‘.‘; 29 } 30 return; 31 } 32 int solutions; 33 };
标签:style blog http color io for ar div log
原文地址:http://www.cnblogs.com/moderate-fish/p/3938318.html