码迷,mamicode.com
首页 > 其他好文 > 详细

N-Queens II

时间:2014-08-27 10:54:07      阅读:206      评论:0      收藏:0      [点我收藏+]

标签: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.

bubuko.com,布布扣

思路:穷举所有合法的摆法。

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

 

N-Queens II

标签:style   blog   http   color   io   for   ar   div   log   

原文地址:http://www.cnblogs.com/moderate-fish/p/3938318.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!