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

LeetCode – Refresh – N-Queens

时间:2015-03-21 09:44:49      阅读:115      评论:0      收藏:0      [点我收藏+]

标签:

Brute Force:

 1 class Solution {
 2 public:
 3     bool notExist(vector<int> rec, int level, int current) {
 4         for (int i = 0; i < level; i++) {
 5             if (rec[i] == current) return false;
 6             if (fabs(rec[i] - current) == fabs(level - i)) return false;
 7         }
 8         return true;
 9     }
10     void genQueen(vector<int> rec, vector<string> &result) {
11         for (int i = 0; i < rec.size(); i++) {
12             ostringstream oss;
13             for (int j = 0; j < rec.size(); j++) {
14                 if (rec[i] == j) oss << Q;
15                 else oss << .;
16             }
17             result.push_back(oss.str());
18         }
19     }
20     void getQueen(vector<vector<string> > &result, vector<int> rec, int n, int level) {
21         if (level == n) {
22             result.push_back(vector<string>());
23             genQueen(rec, result.back());
24             return;
25         }
26         for (int i = 0; i < n; i++) {
27             if (notExist(rec, level, i)) {
28                 rec[level] = i;
29                 getQueen(result, rec, n, level+1);
30             }
31         }
32     }
33     vector<vector<string> > solveNQueens(int n) {
34         vector<vector<string> > result;
35         getQueen(result, vector<int> (n,0), n, 0);
36         return result;
37     }
38 };

 

LeetCode – Refresh – N-Queens

标签:

原文地址:http://www.cnblogs.com/shuashuashua/p/4355149.html

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