poj 2488 A Knight's Journey(简单dfs)
2014-06-03 19:33
423 查看
http://poj.org/problem?id=2488
大致题意:给一个p*q的方格,p代表行数(1,2,3....),q代表列数(A,B,C....),要求输出骑士从任意一点出发经过所有点的路径,必须按字典序输出;路径不存在输出impossible示)。骑士可以一步到达他周围的八个格子(如题所示)
思路:基础的dfs,注意的是按字典序输出路径必须按dir[8][2]
= {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}}的顺序;
大致题意:给一个p*q的方格,p代表行数(1,2,3....),q代表列数(A,B,C....),要求输出骑士从任意一点出发经过所有点的路径,必须按字典序输出;路径不存在输出impossible示)。骑士可以一步到达他周围的八个格子(如题所示)
思路:基础的dfs,注意的是按字典序输出路径必须按dir[8][2]
= {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}}的顺序;
而且起点必须是A1。
#include <stdio.h> #include <iostream> #include <algorithm> #include <set> #include <map> #include <vector> #include <math.h> #include <string.h> #include <queue> #include <string> #define LL long long #define _LL __int64 #define eps 1e-8 using namespace std; const int INF = 0x3f3f3f3f; const int maxn = 26; const int maxm = 1010; int dir[8][2] = {{-1,-2},{1,-2},{-2,-1},{2,-1},{-2,1},{2,1},{-1,2},{1,2}}; int n,m; int vis[maxn][maxn]; struct node { int x; int y; }ans[30]; bool dfs(int x, int y ,int step) { vis[x][y] = 1; ans[step] = ((struct node){x,y}); if(step == n*m) return true; //递归边界 for(int d = 0; d < 8; d++) { int xx = x + dir[d][0]; int yy = y + dir[d][1]; if(xx >= 1 && xx <= n && yy >= 1 && yy <= m && !vis[xx][yy]) if(dfs(xx,yy,step+1)) return true; } vis[x][y] = 0; //走到这一步,说明(x,y)走不通,所以要重新标记为0 return false; } int main() { int test; scanf("%d",&test); for(int item = 1; item <= test; item++) { scanf("%d %d",&n,&m); memset(vis,0,sizeof(vis)); printf("Scenario #%d:\n",item); if(dfs(1,1,1)) { for(int i = 1; i <= n*m; i++) printf("%c%d",ans[i].y-1+'A',ans[i].x); printf("\n\n"); } else printf("impossible\n\n"); } return 0; }
相关文章推荐
- POJ 2488 简单 DFS
- POJ2488——简单DFS
- poj2488 A Knight's Journey(简单dfs)
- poj2488 A Knight's Journey 简单DFS 注意搜索步骤
- poj 2488 A Knight's Journey (dfs)
- POJ 2488 A Knight's Journey (dfs)
- POJ 1111 Image Perimeters 简单DFS
- POJ 1111 Image Perimeters 简单DFS
- POJ 2386 Lake Counting 简单的DFS搜索
- poj 2488 A Knight's Journey (简单dfs+打印路径)
- poj 2488 DFS
- POJ 2488 爵士游行问题--DFS遍历
- POJ2488 A Knight's Journey(DFS)
- poj 2488 DFS
- POJ 2488 DFS
- POJ 2488 A Knight's Journey(经典DFS)
- POJ 3051 Satellite Photographs 简单DFS
- POJ_2488_DFS
- poj 2488 A Knight's Journey (dfs)
- poj2258 简单dfs The Settlers of Catan