红桃J

用心写好每行完美的代码,远比写一堆更有价值

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

第一个的代码:

 1 #include<iostream>
 2 #include<vector>
 3 
 4 using namespace std;
 5 
 6 bool isLegal(int i, int j, vector<string> &current)
 7 {
 8     int size = current.size();
 9     int x = i-1, y = j;
10     while (x >= 0)
11     {
12         if (current[x][y] == 'Q')
13             return false;
14         x--;
15     }
16     x = i-1;
17     y = j - 1;
18     while (x >= 0 && y >= 0)
19     {
20         if (current[x][y] == 'Q')
21             return false;
22         x--;
23         y--;
24     }
25     x = i - 1;
26     y = j + 1;
27     while (x >= 0 && y < size)
28     {
29         if (current[x][y] == 'Q')
30             return false;
31         x--;
32         y++;
33     }
34     return true;
35 }
36 
37 void getResult(int row, int index, vector<vector<string>> &result, vector<string> &current, int size)
38 {
39     if (row == size)
40         result.push_back(current);
41     else
42     {
43         while (index < size)
44         {
45             current[row][index] = 'Q';
46             if (isLegal(row, index, current))
47                 getResult(row + 1, 0, result, current, size);
48             current[row][index] = '.';
49             index++;
50         }
51     }
52 }
53 
54 vector<vector<string>> solveNQueens(int n) 
55 {
56     vector<vector<string>> result;
57     string s = "";
58     for (int i = 0; i < n; i++)
59         s.push_back('.');
60     vector<string> current(n, s);
61     getResult(0, 0, result, current, n);
62     return result;
63 }
64 
65 int main()
66 {
67     vector<vector<string>> result = solveNQueens(4);
68     for (int i = 0; i < result.size(); i++)
69     {
70         for (int j = 0; j < result[i].size(); j++)
71             cout << result[i][j].c_str() << endl;
72         cout << "-_________________________________________-" << endl;
73     }
74     return 0;
75 }

第二个的代码:
得,忘了保存了,算了,不贴了,这题也就做到这份上了,讨论区里那个用位的我真是佩服死你啦。。。。。!!!!!!!!!

posted on 2015-07-01 20:01  红桃J  阅读(170)  评论(0编辑  收藏  举报