首页 > 其他 > 详细

zoj 1091 BFS简单搜索

时间:2014-03-21 13:05:41      阅读:325      评论:0      收藏:0      [点我收藏+]
bubuko.com,布布扣
/*
题意:knight从一个位置移动到另一位置,求最少移动多少步

题解:BFS
*/
#include <cstdio>
#include <cstring>
#include <queue>

using namespace std;

int dir[8][2] = {{-2,-1},{-1,-2},{1,-2},{2,-1},{2,1},{1,2},{-1,2},{-2,1}};//八个方向

bool m[10][10];

struct point
{
    int x,y;
    int deep;
};

int bfs(int sx, int sy, int ex, int ey)
{
    if (sx == ex && sy == ey)
        return 0;
    struct point start,end;
    start.x = sx;
    start.y = sy;
    start.deep = 0;
    end.x = ex;
    end.y = ey;
    memset(m,false,sizeof(m));
    queue<struct point> Q;
    Q.push(start);
    int ret = 0;
    bool flag = false;
    while (!Q.empty())
    {
        struct point tmp,t = Q.front();
        Q.pop();
        m[t.x][t.y] = true;
        for(int i=0; i<8; i++)
        {
            int tx = t.x+dir[i][0];
            int ty = t.y+dir[i][1];
            if (1<=tx && tx<=8 && 1<=ty && ty<=8 && !m[tx][ty])
            {
                if (tx == ex && ty == ey)
                    return t.deep+1;
                tmp.x = tx;
                tmp.y = ty;
                tmp.deep = t.deep+1;
                Q.push(tmp);
                m[tx][ty] = true;
            }
        }
    }
    return ret;
}

int main(void)
{
    char s1[5],s2[5];
    while (scanf("%s%s",s1,s2) == 2)
    {
        printf("To get from %s to %s takes %d knight moves.\n",s1,s2,bfs(s1[0]-a+1,s1[1]-0,s2[0]-a+1,s2[1]-0));
    }
    return 0;
}
bubuko.com,布布扣

zoj 1091 BFS简单搜索,布布扣,bubuko.com

zoj 1091 BFS简单搜索

原文:http://www.cnblogs.com/toufu/p/3614927.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!