标签:des c style class blog code
题目链接:
http://poj.org/problem?id=2243
题目:
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 10932 | Accepted: 6171 |
Description
Input
Output
Sample Input
e2 e4 a1 b2 b2 c3 a1 h8 a1 h7 h8 a1 b1 c3 f6 f6
Sample Output
To get from e2 to e4 takes 2 knight moves. To get from a1 to b2 takes 4 knight moves. To get from b2 to c3 takes 2 knight moves. To get from a1 to h8 takes 6 knight moves. To get from a1 to h7 takes 5 knight moves. To get from h8 to a1 takes 6 knight moves. To get from b1 to c3 takes 1 knight moves. To get from f6 to f6 takes 0 knight moves.
Source
这道题目是搜索的入门提。。我用两种方法写了一下。。。
bfs版本:
#include<cstdio> #include<queue> #include <vector> #include<iostream> #include<cstring> #include<algorithm> const int maxn=10; using namespace std; bool vis[maxn][maxn]; int move[8][2]={{-1,2},{1,2},{-1,-2},{1,-2},{-2,1},{2,1},{-2,-1},{2,-1}}; int step[maxn][maxn]; struct Map { int x,y; }; int check(int x,int y) { if(x>=1&&y>=1&&y<=8&&x<=8) return 1; return 0; } int bfs(int sx,int sy,int ex,int ey) { queue<Map>q; Map a; a.x=sx; a.y=sy; q.push(a); vis[sx][sy]=true; while(!q.empty()) { Map temp=q.front(); q.pop(); for(int i=0;i<8;i++) { int tx=temp.x+move[i][0]; int ty=temp.y+move[i][1]; if(check(tx,ty)&&!vis[tx][ty]) { step[tx][ty]=step[temp.x][temp.y]+1; vis[tx][ty]=true; if(tx==ex&&ty==ey) return step[ex][ey]; Map tmp; tmp.x=tx; tmp.y=ty; q.push(tmp); } } } } int main() { int sx,sy,ex,ey; char s,s1,c; while(scanf("%c%d%c%c%d",&s,&sy,&c,&s1,&ey)!=EOF) { memset(vis,false,sizeof(vis)); memset(step,0,sizeof(step)); sx=s-'a'+1; ex=s1-'a'+1; step[sx][sy]=0; if(sx==ex&&sy==ey) printf("To get from %c%d to %c%d takes %d knight moves.\n",s,sy,s1,ey,0); else printf("To get from %c%d to %c%d takes %d knight moves.\n",s,sy,s1,ey,bfs(sx,sy,ex,ey)); getchar(); } return 0; }
#include<cstdio> #include<iostream> #include<cstring> #include<algorithm> #include<cstdlib> #define INF 0x3f3f3f3f const int maxn=10; using namespace std; bool vis[maxn][maxn]; int step[maxn][maxn]; int ans,ex,ey; int dx[8]={-1,-1,1,1,2,2,-2,-2}; int dy[8]={2,-2,2,-2,1,-1,1,-1}; void dfs(int sx,int sy,int depth) { if(sx<1||sy<1||sx>8||sy>8||depth>=ans) return; if(sx==ex&&sy==ey) { ans=min(ans,depth); return; } if(!vis[sx][sy]) { vis[sx][sy]=true; step[sx][sy]=depth; } else { if(step[sx][sy]<=depth) return; step[sx][sy]=depth; } for(int i=0;i<8;i++) { int tx=sx+dx[i]; int ty=sy+dy[i]; dfs(tx,ty,depth+1); } } int main() { char s,s1,c; int sx,sy; while(scanf("%c%d%c%c%d",&s,&sy,&c,&s1,&ey)!=EOF) { memset(vis,false,sizeof(vis)); memset(step,INF,sizeof(step)); sx=s-'a'+1; ex=s1-'a'+1; ans=10000; dfs(sx,sy,0); printf("To get from %c%d to %c%d takes %d knight moves.\n",s,sy,s1,ey,ans); getchar(); } return 0; }
标签:des c style class blog code
原文地址:http://blog.csdn.net/u014303647/article/details/27710749