N-Queens II

代码:

 1     int result;
 2     void search(int line, int total, vector<bool> &col, vector<bool> &left, vector<bool> &right){
 3         if(line == total){
 4             result++;
 5             return;
 6         }
 7         int i;
 8         for(i = 0; i < total; i++){
 9             if(col[i] && left[line+i] && right[line+total-i-1]){
10                 col[i] = false;
11                 left[line+i] = false;
12                 right[line+total-i-1] = false;
13                 search(line+1, total, col, left, right);
14                 col[i] = true;
15                 left[line+i] = true;
16                 right[line+total-i-1] = true;
17             }
18         }
19     }
20     int totalNQueens(int n) {
21         // IMPORTANT: Please reset any member data you declared, as
22         // the same Solution instance will be reused for each test case.
23         result=0;
24         vector<bool> col(n, true), left(2*n-1, true), right(2*n-1, true);
25         search(0, n, col, left, right);
26         return result;
27     }

 

posted on 2013-11-03 22:46  waruzhi  阅读(200)  评论(0编辑  收藏  举报

导航