zoj 1091 && hdu 1372 Knight Moves

来源:互联网 发布:ping ip加端口 编辑:程序博客网 时间:2024/04/26 16:15

题意:给定起点和终点,求最少需几步完成。(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;}


0 0
原创粉丝点击