POJ 2488 A Knight's Journey(DFS——骑士周游问题)

//要按字典序输出,所以要注意搜索顺序 //最后一行不能留空行 //唉,搜都要写这么久,还WA了那么多次,太弱了我 #include<iostream> using namespace std; int Case,X,Y; bool vis[50][50],ok; int dir[8][2] = {-1,-2,1,-2,-2,-1,2,-1,-2,1,2,1,-1,2,1,2}; int path[30][2]; bool legal(int x,int y) { if(x < 1 || x > X || y < 1 || y > Y) return false; else return true; } void dfs(int x,int y,int step) { if(ok) return; vis[x][y] = 1; path[step][0] = x;//记录路径 path[step][1] = y; if(step == X*Y) { ok = 1; return; } for(int i = 0;i < 8;++i) { if(legal(x+dir[i][0],y+dir[i][1]) && !vis[x+dir[i][0]][y+dir[i][1]]) dfs(x+dir[i][0],y+dir[i][1],step+1); } vis[x][y] = 0;//回溯出口修改访问变量 } int main() { //freopen(“in.txt”,”r”,stdin); scanf(“%d”,&Case); int t = 0; while(Case–) { scanf(“%d%d”,&X,&Y); memset(vis,0,sizeof(vis)); ok = 0; dfs(1,1,1); printf(“Scenario #%d:/n”,++t); if(!ok) printf(“impossible/n”); else { for(int i = 1;i <= X*Y;++i) printf(“%c%d”,path[i][1]+’A’-1,path[i][0]); printf(“/n”); } if(Case != 0) printf(“/n”); } return 0; } 

    原文作者:骑士周游问题
    原文地址: https://blog.csdn.net/ChinaCzy/article/details/5833400
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞