UVa 439-Knight Moves

来源:互联网 发布:linux怎么禁ping 编辑:程序博客网 时间:2024/06/06 00:44

题目链接:https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=380
非常简单基础的一道BFS题。不同一般的BFS的是,马的移动方式。国际象棋马的走法和中国象棋一样,都是走日字。不过国际象棋总棋子是走格子,而中国象棋是走交叉点。下惯了中国象棋的我还是很不习惯这一点的。不过搞清楚了马的走法就好办了。我设置的马的八个遍历方向是按照顺时针来的。以下是代码:

#include<cstdio>#include<cstdlib>#include<cstring>#include<queue>using namespace std;struct Vertex{    int r;    int c;    int level;    Vertex(){};    Vertex(int _r,int _c,int _level):r(_r),c(_c),level(_level){};};int map[8][8];char str1[3];char str2[3];int visited[8][8];int dir[8][2]={{-1,-2},{-1,2},{1,2},{1,-2},{-2,-1},{-2,1},{2,1},{2,-1}};//遍历的方向,即马的走法Vertex e;int BFS(int r,int c){    int i;    queue<Vertex> qu;    visited[r][c]=1;    qu.push(Vertex(r,c,0));     while(!qu.empty())    {        Vertex v=qu.front();         qu.pop();        if(v.r==e.r&&v.c==e.c) return v.level;        for(i=0;i<8;i++)        {            int r1=v.r+dir[i][0];            int c1=v.c+dir[i][1];            if(r1>=0 && r1<8 && c1>=0 && c1<8)            {                if(visited[r1][c1]==0)                {                    qu.push(Vertex(r1,c1,v.level+1));                    visited[r1][c1]=1;                }            }        }    }}int main(){    //freopen("input.txt","r",stdin);    //freopen("output.txt","w",stdout);    while(scanf("%s%s",str1,str2)!=EOF)    {        memset(map,0,sizeof(map));        memset(visited,0,sizeof(visited));        //将字符转化成数字坐标,第一个字符是列数,第二个字符是行数        e.r=str2[1]-49;        e.c=str2[0]-97;        int l=BFS(str1[1]-49,str1[0]-97);        printf("To get from %s to %s takes %d knight moves.\n",str1,str2,l);    }}
0 0
原创粉丝点击