因为要遍历全部点, 所以肯定可以从A1 出发。/
dfs 一般结构 bool dfs(arguments) { if (Search to The End Of DFS)return true; Save Some Arguments; for (every NextNode) { Save Some NextNode's Arguments if (Conditions is Satisfied) { Change & Save Status; if (dfs(NextNode's Arguments)) return true; Return Status; } } return false; } main() { Change & Save First Status; if (dfs(first Status's arguments)) do. }
#include <iostream> #include <string.h> using namespace std; int s[8][2] = {-2, -1, -2, 1, -1, -2, -1, 2, 1, -2, 1, 2, 2, -1, 2, 1}; bool dfs(int x, int y, int p, int q, int step, bool board[27][27], char* path) { if (step == p * q) { return true; } int xx , yy; for (int i = 0; i < 8; i++) { xx = x + s[i][0]; yy = y + s[i][1]; if (xx > 0 && xx <= q && yy > 0 && yy <= p && board[yy][xx] == false) { board[yy][xx] = true; path[step*2] = (char)(xx - 1 + 'A'); path[step*2 + 1] = (char)(yy + '0'); if (dfs(xx, yy, p, q, step + 1, board, path)) { return true; } board[yy][xx] = false; } } return false; } int main() { bool board[27][27]; int p, q; char path[27*27]; int c; cin>>c; for (int i = 0; i < c; i++) { cin>>p>>q; memset(board, 0, sizeof(board)); memset(path, 0, sizeof(path)); board[1][1] = true; path[0] = 'A'; path[1] = '1'; cout<<"Scenario #"<<i+1<<":/n"; if (dfs(1,1, p, q, 1, board, path)) cout<<path<<endl<<endl; else cout<<"impossible"<<endl<<endl; } }