递归_百炼2754 八皇后问题

Runtime Error了一发,原来是把solve函数写进了while(T--){}  里面了,哎,粗心!

深度优先搜索,比较重要的部分就是要接着上一次的状态

 1 #define _CRT_SECURE_NO_WARNINGS  
 2 #include <stdio.h>
 3 #include <math.h>
 4 #include <algorithm>
 5 #include <stdlib.h>
 6 #include <vector>
 7 #include <map>
 8 #include <queue>
 9 #include <string>
10 #include <iostream>
11 #include <ctype.h>
12 #include <string.h>
13 #include <set>
14 #include <stack>
15 #include<functional>
16 using namespace std;
17 #define Size 27
18 #define maxn  1<<30
19 int  ans[93][9];
20 int no = 1;
21 bool canSet(int x, int y){//是否可以在x,y的位置放置棋子
22     for (int i = 1; i <x; i++){//枚举前面放置的x-1行
23         if (i + ans[no][i] == x + y) return false;//斜率小于0的线
24         if (ans[no][i] == y) return false;
25         if (ans[no][i] - i == y - x) return false; //斜率大于0的线
26     }
27     return true;
28 }
29 void solve(int x){//在第x行放置棋子
30     if (x > 8) {
31         for (int i = 1; i <= 8; i++)//继承上一次的状态,以便在上一次的状态上接着深度优先遍历
32             ans[no + 1][i] = ans[no][i];
33         no++;
34         return;
35     }
36     for (int i = 1; i <= 8; i++){//枚举列
37         if (canSet(x, i))
38         {
39             ans[no][x] = i;
40             solve(x + 1);
41         }
42     }
43 }
44 int main(){
45 
46     int T;
47     cin >> T;
48     solve(1);//往第1行放旗子
49     while (T--){
50         int j;
51         cin >> j;
52         for (int i = 1; i <= 8;i++)
53         cout << ans[j][i];
54         cout << endl;
55     }
56     system("pause");
57     return 0;
58 }

 

posted @ 2018-01-27 23:28  MapReduce  阅读(187)  评论(0编辑  收藏  举报