把起点设为A 1点,DFS找序列
#include <iostream> #include <cstdio> #include <cstring> using namespace std; int r,c,flag,map[30][30]; int lc[1000][2]; int dir[8][2]={{-1,-2},{1,-2},{-2,-1},{2,-1}, {-2,1},{2,1},{-1,2},{1,2}}; bool judge(int x,int y) { if (x <= 0 || x > r || y <= 0 || y > c) return false; if (map[x][y] == 1) return false; return true; } void dfs(int x,int y,int cnt) { int tx,ty,i; map[x][y]=1; lc[cnt][0]=x; lc[cnt][1]=y; if (cnt+1 == r*c) { for (i=0; i<=cnt; i++) printf("%c%d",lc[i][1]-1+'A',lc[i][0]); printf("\n\n"); flag=1; return ; } for (i=0; i<8; i++) { tx=x+dir[i][0]; ty=y+dir[i][1]; if (judge(tx,ty)) { dfs(tx,ty,cnt+1); if (flag == 1) break; } } map[x][y]=0; } int main() { int i,T,prob; scanf("%d",&T); prob=1; while (T--) { scanf("%d%d",&r,&c); flag=0; memset(map,0,sizeof(map)); printf("Scenario #%d:\n",prob); dfs(1,1,0); prob++; if (flag == 0) printf("impossible\n\n"); } }