poj 2488
深度遍历,记住字典序很重要
1 #include <iostream> 2 #include <string> 3 #include <vector> 4 #include <cstdlib> 5 #include <cmath> 6 #include <map> 7 #include <algorithm> 8 #include <list> 9 #include <ctime> 10 #include <set> 11 #include <string.h> 12 #include <queue> 13 #include <cstdio> 14 #define CLR(arr, what) memset(arr, what, sizeof(arr)) 15 typedef long long ll; 16 const int MAX = 28; 17 using namespace std; 18 19 int visit[MAX][MAX]; 20 int dx[] = { -2, -2, -1, -1, 1, 1, 2, 2 }; 21 int dy[] = { -1, 1, -2, 2, -2, 2, -1, 1 }; 22 int row, col; 23 vector<int> path; 24 void print() { 25 int sz = path.size(); 26 for (int i = sz / 2 - 1; i >= 0; i--) { 27 cout << (char) ('A' + path[i * 2]) << path[i * 2 + 1] + 1; 28 } 29 } 30 bool dfs(int total, int x, int y) { 31 32 bool judge; 33 if (x < 0 || x >= row || y < 0 || y >= col) { 34 return false; 35 } else if (visit[x][y] == 1) { 36 return false; 37 } else { 38 if (total == row * col) { 39 path.push_back(x); 40 path.push_back(y); 41 return true; 42 } 43 44 visit[x][y] = 1; 45 for (int i = 0; i < 8; i++) { 46 judge = dfs(total + 1, x + dx[i], y + dy[i]); 47 if (judge) { 48 path.push_back(x); 49 path.push_back(y); 50 return true; 51 } 52 } 53 visit[x][y] = 0; 54 return false; 55 } 56 } 57 int main() { 58 int n; 59 bool judge; 60 cin >> n; 61 for (int i = 0; i < n; i++) { 62 path.clear(); 63 CLR(visit, 0); 64 cin >> col >> row; 65 judge = dfs(1, 0, 0); 66 cout << "Scenario #" << i + 1 << ":\n"; 67 if (judge) { 68 print(); 69 cout << endl; 70 } else { 71 cout << "impossible" << endl; 72 } 73 cout << endl; 74 } 75 return 0; 76 }