洛谷P1443 马的遍历

#include<iostream>
#include<algorithm>
#include<queue>
#include<cstring>
using namespace std;
int n, m, xs, ys;
int arr[8][2] = { {-1,-2},{-2,-1},{-2,1},{-1,2},{1,2},{2,1},{2,-1},{1,-2} };//马的八条路线
int horse[450][450];//记录坐标处的最少步数
struct tem
{
    int x;
    int y;
}temp;//记录下一次的位置
queue<tem>h;//队列存储当前马的位置
int main()
{     
    freopen("title.in", "r", stdin);
    memset(horse, -1, 450 * 450 * sizeof(int));//将初始位置最少步数设为-1,方便到达不了时可以直接输出
    cin >> n >> m >> xs>> ys;
    horse[xs][ys] = 0;//初始化开头,注意此时原点是从(1,1)开始
    temp.x = xs, temp.y = ys;
    h.push(temp);
    while (!h.empty())
    {
        for (int i = 0; i < 8; i++)
        {
            temp.x = h.front().x + arr[i][0];
            temp.y = h.front().y + arr[i][1];
            if (temp.x > 0 && temp.y > 0&& temp.x <=n&& temp.y <=m&& horse[temp.x][temp.y] ==-1)
            {
                horse[temp.x][temp.y] = horse[h.front().x][h.front().y] + 1;;
                h.push(temp);
            }
        }
        h.pop();
    }
    for (int i = 1; i <= n; i++)
    {
        for (int t = 1; t <= m; t++)
        {
            printf("%-5d", horse[i][t]);//“-”代表左对齐
        }
        cout << endl;
    }
     return 0;
}

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值