码迷,mamicode.com
首页 > 编程语言 > 详细

Leetcode: N-Queens C++

时间:2014-07-31 23:23:50      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   io   for   ar   div   c++   

 1 class Solution {
 2 public:
 3     vector<vector<string> > solveNQueens(int n) {
 4      vector<vector<string>> res;
 5      vector<vector<string>> pre_res;
 6      for(int i = 0; i < n; i++){
 7          res.clear();
 8          for(int j = 0; j < n; j++){
 9              if(i == 0){
10                  vector<string> tmp;
11                  string s;
12                  s.assign(n,.);
13                  s[j] = Q;
14                  tmp.push_back(s);
15                  res.push_back(tmp);
16              }else{
17                  for(int k = 0; k < pre_res.size(); k++){
18                      if(not_attack(pre_res[k],i,j,n)){
19                          string s;
20                          s.assign(n,.);
21                          s[j] = Q;
22                          vector<string> tmp;
23                          tmp = pre_res[k];
24                          tmp.push_back(s);
25                          res.push_back(tmp);
26                      }
27                  }
28                  
29              }
30          }
31          pre_res = res;
32      }
33      return pre_res;   
34     }
35     bool not_attack(vector<string> cb, int row,int col, int n){
36         int i = 0;
37         while(i < row){
38             if(cb[i][col] == Q) return false;
39             i++;
40         }
41         i = row - 1;
42         int j = col - 1;
43         while(i >= 0 && j >= 0){
44             if(cb[i][j] == Q) return false;
45             i--;
46             j--;
47         }
48         i = row - 1;
49         j = col + 1;
50         while(i >= 0 && j < n){
51             if(cb[i][j] == Q) return false;
52             i--;
53             j++;
54         }
55         return true;
56     }
57 };

 

Leetcode: N-Queens C++,布布扣,bubuko.com

Leetcode: N-Queens C++

标签:style   blog   color   io   for   ar   div   c++   

原文地址:http://www.cnblogs.com/Kai-Xing/p/3883561.html

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