您的位置:首页 > 其它

zoj 1091 && hdu 1372 Knight Moves

2014-01-08 22:49 260 查看
题意:给定起点和终点,求最少需几步完成。(bfs)

总结:queue<node> q;在函数外,每次用都要记得清空。

#include<cstdio>
#include<queue>
#include<cstring>
#include<iostream>
using namespace std;

int dx[]={-1,-2,-2,-1,1,2,2,1};
int dy[]={-2,-1,1,2,2,1,-1,-2};
bool vis[10][10];
struct node
{
    int x,y;
    int step;
}st,ed;

queue<node> q;

bool ok(node u)
{
    if(u.x>=1 && u.x<=8 && u.y>=1 && u.y<=8)
        return true;
    return false;
}

int bfs()
{
    while(!q.empty())
        q.pop();
    st.step=0;
    q.push(st);

    node cur,next;
    while(!q.empty())
    {
        cur = q.front();
        if(cur.x==ed.x && cur.y == ed.y)
            return cur.step;
        q.pop();
        for(int i=0;i<8;i++)
        {
            next.x = cur.x+dx[i];
            next.y = cur.y+dy[i];
            if(ok(next) && !vis[next.x][next.y])
            {
                vis[next.x][next.y]=true;
                next.step = cur.step+1;
                q.push(next);
            }
        }
    }
}

int main()
{
    char a,c;
    int b,d;
    while(scanf("%c%d %c%d",&a,&b,&c,&d)!=EOF)
    {
        memset(vis,0,sizeof(vis));
        st.x = a-'a'+1;
        st.y = b;
        ed.x = c-'a'+1;
        ed.y = d;
        //cout<<st.x<<' '<<st.y<<' '<<ed.x<<' '<<ed.y<<endl;
        int ans = bfs();
        printf("To get from %c%d to %c%d takes %d knight moves.\n",a,b,c,d,ans);
        getchar();
    }
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: