HDU 1372——DFS

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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值