p1443马的遍历

https://www.luogu.org/problemnew/show/P1443

思路:深度遍历,能走的就走,裸模板

#include <iostream>
#include <cstdio>
#include <cstring>
#include<iomanip>
#include<string>
#include<queue>
using namespace std;

struct node
{
    int x, y;
};
queue<node>Q;
int n, m,sx, sy;
int a[401][401];
//int step = 1;
int dx[]={-2, -2, -1, 1, 2, 2, 1, -1};//这个自己画图可以看是怎么得来的
int dy[]={-1, 1, 2, 2, 1, -1, -2, -2};
void bfs(int x, int y)
{
    a[x][y] = 0;
    node tmpnode;
    tmpnode.x = x;
    tmpnode.y = y;
    Q.push(tmpnode);
    

    while(!Q.empty())
    {
        //cout<<"haha";
        //system("pause");
        node fnode = Q.front();
        Q.pop();

        for(int i = 0; i < 8; i++)
        {
            int x0 = fnode.x +dx[i];
            int y0 = fnode.y + dy[i];
            if(x0 >= 1 && x0 <= n && y0>=1 && y0<=m && a[x0][y0] == -1)
            {
                //cout<<x0<<" "<<y0<<" "<<a[fnode.x][fnode.y] + 1<<endl;
                //system("pause");
                a[x0][y0] = a[fnode.x][fnode.y]+1;//步数是父节点+1
                tmpnode.x = x0;
                tmpnode.y = y0;
                Q.push(tmpnode);
            }
        }
        //step++;
    }
}
int main()
{

    ios::sync_with_stdio (false);
    cin>>n>>m>>sx>>sy;
    for(int i = 1; i <= n; i++)
        for(int j = 1; j <= m; j++)
            a[i][j] = -1;
    bfs(sx, sy);

    for(int i = 1; i <= n; i++)
    {
        for(int j = 1; j <= m; j++)
            cout<<left<<setw(5)<<a[i][j];//左对齐和宽度是5输出
            //cout<<a[i][j]<<" ";
        
        cout<<endl;
    
    }
    //system("pause");

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值