题目大意:骑士遍历给定p*q棋盘,列是从'A'开始,找到一条字典序最小的遍历路径。 // 236k 47ms #include <iostream> #include <cstring> using namespace std; typedef class { public: int row; char col; } location; bool visit['Z'+1][27]; int row, col; int x, y; // 下个选择的点 void path(int i, int j, int num) { switch (num) { case 1: {x=i-1; y=j-2; break;} // 按字典序走 case 2: {x=i+1; y=j-2; break;} case 3: {x=i-2; y=j-1; break;} case 4: {x=i+2; y=j-1; break;} case 5: {x=i-2; y=j+1; break;} case 6: {x=i+2; y=j+1; break;} case 7: {x=i-1; y=j+2; break;} case 8: {x=i+1; y=j+2; break;} } } bool DFS(location *way, int i, int j, int step) { visit[i][j] = true; way[step].row = i; way[step].col = j; if (step == row*col) { return true; } for (int k = 1; k <= 8; ++k) { path(i, j, k); int ii = x, jj = y; if (!visit[ii][jj] && ii >= 1 && ii <= row && jj >= 'A' && jj <= col+'A'-1) { if (DFS(way, ii, jj, step+1)) { return true; } } } visit[i][j] = false; return false; // 当前位置是错误的,擦除 } int main() { //freopen("temp.txt", "r", stdin); int t = 1, test; cin >> test; while (t <= test) { memset(visit, 0, sizeof(visit)); cin >> row >> col; location *way = new location[row*col+1]; bool success = false; for (int j = 'A'; j <= 'A'+col-1; ++j) { // 因为要字典序排序,所以先从列'A'排 for (int i = 1; i <= row; ++i) { if (DFS(way, i, j, 1)) { cout<<"Scenario #"<<t++<<':'<<endl; for (int k = 1; k <= row*col; ++k) { cout << way[k].col << way[k].row; } cout << endl << endl; success = true; break; } } if (success) { break; } } if (!success) { cout<<"Scenario #"<<t++<<':'<<endl; cout<<"impossible"<<endl<<endl; } } return 0; }