1. 程式人生 > >遞歸_百煉2754 八皇後問題

遞歸_百煉2754 八皇後問題

sys return function tor mes 函數 sta esp true

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 }

遞歸_百煉2754 八皇後問題