标签:
比较典型的深搜,注意1,最后的输出格式,我imposiable后面忘记endl了,结果PE了两次,有点可惜; 2.最后要以字典序输出
1 #include<iostream> 2 #include<string.h> 3 using namespace std; 4 5 #define MAX 8 6 7 int p,q; 8 int board[MAX][MAX]; 9 int steps[MAX*MAX]; 10 11 int dir[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}}; 12 13 14 bool DFS(int x,int y,int step) { 15 16 if(step == p * q) 17 return true; 18 19 bool flag = false; 20 int tempx,tempy; 21 22 for(int i=0;i<8;i++) { 23 24 25 tempx = x + dir[i][0]; 26 tempy = y + dir[i][1]; 27 28 if(!board[tempx][tempy] && tempx < p && tempy < q && tempx >= 0 && tempy >= 0) { 29 board[tempx][tempy] = 1; 30 if(DFS(tempx,tempy,step+1)) 31 { 32 steps[step-1] = i; 33 flag = true; 34 break; 35 } 36 else { 37 board[tempx][tempy] = 0; 38 } 39 40 } 41 42 } 43 44 return flag; 45 46 } 47 48 49 50 51 int main() { 52 53 54 int count; 55 56 cin >> count; 57 int num = count; 58 while(num--) { 59 60 cin>> p >> q; 61 62 memset(board,0,sizeof(int)*MAX*MAX); 63 memset(steps,0,sizeof(int)*MAX*MAX); 64 board[0][0] = 1; 65 66 cout<<"Scenario #"<<count-num<<":"<<endl; 67 68 if(DFS(0,0,1)) { 69 string s("A1"); 70 int x_offset=0,y_offset=0; 71 72 for(int i=0;i<p*q-1;i++) { 73 74 x_offset += dir[steps[i]][0]; 75 y_offset += dir[steps[i]][1]; 76 77 s.push_back((char)(‘A‘+ y_offset)); 78 s.push_back((char)(‘1‘+ x_offset)); 79 } 80 81 cout<<s<<endl<<endl; 82 } 83 else 84 cout<<"impossible"<<endl<<endl; 85 86 } 87 88 89 return 0; 90 }
标签:
原文地址:http://www.cnblogs.com/haipeng-blog/p/4975820.html