zoukankan      html  css  js  c++  java
  • poj 2243 简单bfs

    链接:http://poj.org/problem?id=2243

    题意:给定棋盘上的两个位置a,b,计算马从a跳到b最少需要多少步。

    思路:要注意象棋中是马走日。然后就用bfs求最小步数。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<queue>
    #include<string>
    #include<cmath>
    #include<algorithm>
    #include<map>
    using namespace std;
    
    
    int flag[9][9];
    map<char,int> m;
    int sx,sy,ex,ey,mins;
    int dir[8][2]={{2,1},{1,2},{-1,2},{-2,1},{-2,-1},{-1,-2},{1,-2},{2,-1}};
    struct point
    {
        int x,y,step;
    };
    queue<point> q;
    
    void bfs(point s)
    {
        bool f=0;
        q.push(s);
        flag[sx][sy]=1;
        while(!q.empty())
        {
            int x,y;
            point t=q.front();
            q.pop();
            for(int i=0;i<8;i++)
            {
                x=t.x+dir[i][0];
                y=t.y+dir[i][1];
                if(x<1 || y<1 || x>8 || y>8 || flag[x][y])
                   continue;
                flag[x][y]=1;
                point p;
                p.x=x;p.y=y;p.step=t.step+1;
                q.push(p);
                if(x==ex && y==ey)
                {
                     mins=p.step;
                     f=1;
                     break;
                }
            }
        }
        if(!f) mins=0;
    }
    int main()
    {
        for(int i=1;i<=8;i++)
            m['a'+i-1]=i;
        char a,b;
        while(~scanf("%c%d %c%d",&a,&sy,&b,&ey))
        {
            getchar();
            sx=m[a];
            ex=m[b];
            point s;
            s.x=sx;s.y=sy;s.step=0;
            memset(flag,0,sizeof(flag));
            bfs(s);
            printf("To get from %c%d to %c%d takes %d knight moves.\n",a,sy,b,ey,mins);
        }
        return 0;
    }

    人生真是无趣啊。。。叹叹

  • 相关阅读:
    textarea组件
    switch组件
    slider组件
    radio组件
    picker-view组件
    picker组件 label组件讲解
    weui 框架
    微信小程序 input 组件
    在php中获取 数据库的内容,返回到页面
    微信小程序 form 组件
  • 原文地址:https://www.cnblogs.com/54zyq/p/3091455.html
Copyright © 2011-2022 走看看