HDU 1372——DFS

来源:互联网 发布:淘宝女装精修图教程 编辑:程序博客网 时间:2024/06/05 04:09
DFS的模板题
题目链接
点击打开链接
#include<iostream>#include<cstring>#include<cstdio>#include<queue>#define MM(x,y) memset(x,y,sizeof(x))using namespace std;struct node{    int x;    int y;    int pos;};queue<node>a;char e[5],s[5];int vis[30][30];int dir[8][2]={{1,2},{2,1},{1,-2},{-2,1},{-1,2},{2,-1},{-1,-2},{-2,-1}};int ex,ey,sx,sy;int dfs(){    while(!a.empty())        a.pop();    int i;    node now,next;    now.x=sx;    now.y=sy;    now.pos=0;    MM(vis,0);    vis[sx][sy]=1;    a.push(now);    while(!a.empty())    {        now=a.front();        a.pop();        if(now.x==ex&&now.y==ey)            return now.pos;        else        {            for(i=0;i<8;i++)            {                int tx=now.x+dir[i][0];                int ty=now.y+dir[i][1];                if(tx>=1&&tx<=8&&ty>=1&&ty<=8&&!vis[tx][ty])                {                    next.x=tx;                    next.y=ty;                    next.pos=now.pos+1;                    vis[tx][ty]=1;                    a.push(next);                }            }        }    }}int main(){    while(cin>>s>>e)    {        sx=s[0]-'a'+1;        sy=s[1]-'0';        ex=e[0]-'a'+1;        ey=e[1]-'0';        cout<<"To get from "<<s<<" to "<<e<<" takes "<<dfs()<<" knight moves."<<endl;    }    return 0;}


原创粉丝点击