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;
}