http://poj.org/problem?id=2488
好久没写回溯,题目要求骑士遍历全图,不能实现就输出“impossible”,首先遍历的
方向要选好,字典序,其次判断遍历了全图的条件就是走了p*q-1步。初始点选取A1即可。
/*Accepted 168K 16MS C++ 1267B 2012-07-23 15:35:53*/ #include<cstdio> #include<cstring> #include<cstdlib> const int MAXN = 30; const int dx[] = {-2, -2, -1, -1, 1, 1, 2, 2}; const int dy[] = {-1, 1, -2, 2, -2, 2, -1, 1}; bool vis[MAXN][MAXN]; int p, q, st, path[MAXN][2]; bool dfs(int x, int y) { int nx, ny, i; if( st == p * q - 1) return true; for( i = 0; i < 8; i ++) { nx = x + dx[i]; ny = y + dy[i]; if( !vis[nx][ny] && nx >= 0 && nx < q && ny >= 0 && ny < p) { vis[nx][ny] = true; ++ st; path[st][0] = nx, path[st][1] = ny; if( dfs(nx, ny)) return true; -- st; vis[nx][ny] = false; } } return false; } int main() { int T, cas, i; scanf( "%d", &T); for( cas = 1; cas <= T; cas ++) { scanf( "%d%d", &p, &q); st = 0; memset(vis, false, sizeof vis); vis[0][0] = true; path[0][1] = path[0][0] = 0; printf( "Scenario #%d:\n", cas); if( dfs(0, 0)) { for( i = 0; i <= st; i ++) printf( "%c%c", 'A' + path[i][0], '1' + path[i][1]); } else printf( "impossible"); printf( "\n\n"); } return 0; }