广搜 象棋格

在一张8*8的象棋盘上,马走日的方式移动,问任意给定的两点pa,pb,问从pa到pb至少需要移动几步。

用 BFS,本题中字符串常量的输入,声明用到了C++中的string类!下为打印样式:


Source:POJ2243
Type:BFS
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <string>
#include <cstdio>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;

int dx[] = { 1,  2,  2,  1, -1, -2, -2, -1};
int dy[] = { 2,  1, -1, -2, -2, -1,  1,  2};
int step[8][8], fa[8][8];//本题没有对路径的要求,加上父亲节点只是为了方便调试
bool vis[8][8];

inline bool inbound(int x, int y)
{
    return(x>=0&&x<8&&y>=0&&y<8);
}

inline int encode(int x, int y) { return x * 8 + y; }

inline int newPos(int old, int method)
{
    int x = old / 8, y = old % 8;
    x += dx[method], y += dy[method];
    if (inbound(x, y) )return encode(x, y);
    else return -1;
}

inline int getx(string s) { return int(s[0] - 'a'); }

inline int gety(string s) { return int(s[1] - '1'); }

int bfs(string _beg, string _tar)
{
    int beg = encode(getx(_beg), gety(_beg));
    int tar = encode(getx(_tar), gety(_tar));
    memset(step, 0, sizeof(step));
    memset(vis, 0, sizeof(vis));
    memset(fa, 0, sizeof(fa));
    queue<int> q; q.push(beg); vis[beg / 8][beg % 8] = 1;
    fa[beg / 8][beg % 8] = beg;
    while (!q.empty())
    {
        int top = q.front(); q.pop();
        if (top == tar) break;//跳出循环后,由于step[][]数组被初始化,所以直接是0.
        for (int j = 0; j < 8; j++)
        {
            int tmp = newPos(top, j);
            if (tmp != -1 && inbound(tmp/8,tmp%8) && !vis[tmp / 8][tmp % 8])
            {
                vis[tmp / 8][tmp % 8] = 1;
                step[tmp / 8][tmp % 8] = step[top / 8][top % 8] + 1;
                fa[tmp / 8][tmp % 8] = top;
                q.push(tmp);
            }
        }
    }
    return step[tar / 8][tar % 8];
}

int main()
{
  string b, t;
  while (cin >> b >> t)
  printf("To get from %s to %s takes %d knight moves.\n", b.c_str(), t.c_str(), bfs(b, t));
  return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值