【BFS练习】POJ 3278 Catch That Cow && CH2501 矩阵距离

POJ 3278 Catch That Cow

用一个vis数组标记一下每个点是否被访问过,否则TLE或者MLE…

#include <queue>
#include <cstdio>
#include <cstring>
#include <iostream>
using namespace std;
const int N=1e5;
int a,b,x,nx,cnt,vis[N+10];
struct node
{
    int x,cnt;
};
queue<node>q;
int main()
{
    ios::sync_with_stdio(false);
    cin>>a>>b;
    if(a>=b){printf("%d\n",a-b);return 0;}
    q.push({a,0});
    vis[a]=1;
    while(!q.empty())
    {
        node tmp=q.front();q.pop();
        x=tmp.x;
        cnt=tmp.cnt;
        if(x==b){printf("%d\n",cnt);break;}
        nx=x+1;
        if(nx>=0&&nx<=N&&!vis[nx])
        {
            vis[nx]=1;
            q.push({nx,cnt+1});
        }
        nx=x-1;
        if(nx>=0&&nx<=N&&!vis[nx])
        {
            vis[nx]=1;
            q.push({nx,cnt+1});
        }
        nx=x*2;
        if(nx>=0&&nx<=N&&!vis[nx])
        {
            vis[nx]=1;
            q.push({nx,cnt+1});
        }
    }
    return 0;
}

《算法竞赛进阶指南》题目练习 CH2501 矩阵距离

从1开始搜索,搜索到0时记录最短步数,保存到ans数组中。

#include <bits/stdc++.h>
using namespace std;
const int N=1010;
char a[N][N];
int n,m,ans[N][N],vis[N][N];
int dir[4][2]={0,1,0,-1,1,0,-1,0};
struct node
{
    int x,y,cnt;
};
queue<node>q;
int main()
{
    ios::sync_with_stdio(false);
    cin>>n>>m;
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
        {
            cin>>a[i][j];
            if(a[i][j]=='1')q.push({i,j,0}),ans[i][j]=0,vis[i][j]=1;
        }
    while(!q.empty())
    {
        node tmp=q.front();q.pop();
        int x=tmp.x,y=tmp.y,cnt=tmp.cnt;
        for(int i=0;i<4;i++)
        {
            int nx=x+dir[i][0];
            int ny=y+dir[i][1];
            if(nx>=1&&nx<=n&&ny>=1&&ny<=m&&!vis[nx][ny])
            {
                vis[nx][ny]=1;
                ans[nx][ny]=cnt+1;
                q.push({nx,ny,cnt+1});
            }
        }
    }
    for(int i=1;i<=n;i++)
        for(int j=1;j<=m;j++)
            j==m?printf("%d\n",ans[i][j]):printf("%d ",ans[i][j]);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

nefu-ljw

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值