ZOJ 1091 Knight Moves

#include <iostream>
#include <stdio.h>
#include <string>
#include <queue>
using namespace std;
int c[9][9];//存放每个位置
int dir[8][2] = { { -2, -1 }, { -2, 1 }, { -1, 2 }, { 1, 2 }, { 2, 1 }, { 2, -1 }, { 1, -2 }, { -1, -2 } };
st\
ruct node
{
    int x, y, count;//xy代表行列数 count代表步数
};
node start, finish;//定义结点分别代表骑士起始位置和终止位置
int bfs()
{
    memset(c, 0, sizeof(c));//数组c内元素全初始化为0
    node pre, cur;//定义结点分别代表骑士上个位置和当前的位置
    start.count = 0;起始位置走过的步数为0
    queue<node> q;//定义一个路径容器适配器
    q.push(start);//把起点放进去
    c[start.x][start.y] = 1;//起点设置为1
    while (!q.empty())//当适配器未被完全清空时
    {
        pre = q.front();//起点节点赋给上个位置节点
        q.pop();//删除赋值后的节点
        if (pre.x == finish.x&&pre.y == finish.y)//移动到终点之后
            return pre.count;//返回值为步数
        for (int i = 0; i < 8; i++)//循环调用8个方向
        {
            cur.x = pre.x + dir[i][0];
            cur.y = pre.y + dir[i][1];//计算当前位置
            if (cur.x<1 || cur.x>8 || cur.y<1 || cur.y>8)continue;//行列数溢出 执行下次循环
            if (c[cur.x][cur.y] == 1)continue;//当前位置为1 执行下次循环
            c[cur.x][cur.y] = 1;//把当前位置赋为1
            cur.count = pre.count + 1;//当前步数比上个位置多一步
            q.push(cur);//把当前节点放入适配器
        }//一个for循环结束 八个方向算完 适配器增加了若干解点
    }//不断重复循环 计算步数
    return -1;
}
int main()
{
    char row, endr;
    int col, endc;
    int min;
    while (cin >> row)
    {
        cin >> col;
        cin >> endr >> endc;
        start.x = row - 'a' + 1;
        start.y = col;
        finish.x = endr - 'a' + 1;
        finish.y = endc;
        if (start.x == finish.x&&start.y == finish.y) min = 0;
        min = bfs();
        printf("To get from %c%d to %c%d takes %d knight moves.\n", row, col, endr, endc, min);
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值