hiho#1478 : 水陆距离 (BFS)

传送门


解题思路:把所有0的点压进queue中,然后就是简单的BFS。


/* ***********************************************
┆  ┏┓   ┏┓ ┆
┆┏┛┻━━━┛┻┓ ┆
┆┃       ┃ ┆
┆┃   ━   ┃ ┆
┆┃ ┳┛ ┗┳ ┃ ┆
┆┃       ┃ ┆
┆┃   ┻   ┃ ┆
┆┗━┓ 马 ┏━┛ ┆
┆  ┃ 勒 ┃  ┆      
┆  ┃ 戈 ┗━━━┓ ┆
┆  ┃ 壁     ┣┓┆
┆  ┃ 的草泥马  ┏┛┆
┆  ┗┓┓┏━┳┓┏┛ ┆
┆   ┃┫┫ ┃┫┫ ┆
┆   ┗┻┛ ┗┻┛ ┆
************************************************ */
//#pragma comment(linker, "/STACK:102400000,102400000")
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

#define rep(i,a,b) for (int i=(a),_ed=(b);i<=_ed;i++)
#define per(i,a,b) for (int i=(a),_ed=(b);i>=_ed;i--)
#define pb push_back
#define mp make_pair
const int inf_int = 2e9;
const long long inf_ll = 2e18;
#define inf_add 0x3f3f3f3f
#define mod 1000000007
#define LL long long
#define ULL unsigned long long
#define MS0(X) memset((X), 0, sizeof((X)))
#define SelfType int
SelfType Gcd(SelfType p,SelfType q){return q==0?p:Gcd(q,p%q);}
SelfType Pow(SelfType p,SelfType q){SelfType ans=1;while(q){if(q&1)ans=ans*p;p=p*p;q>>=1;}return ans;}
#define Sd(X) int (X); scanf("%d", &X)
#define Sdd(X, Y) int X, Y; scanf("%d%d", &X, &Y)
#define Sddd(X, Y, Z) int X, Y, Z; scanf("%d%d%d", &X, &Y, &Z)
#define reunique(v) v.resize(std::unique(v.begin(), v.end()) - v.begin())
#define all(a) a.begin(), a.end()
#define   mem(x,v)      memset(x,v,sizeof(x))
typedef pair pii;
typedef pair pll;
typedef vector vi;
typedef vector vll;
inline int read(){int ra,fh;char rx;rx=getchar(),ra=0,fh=1;while((rx<'0'||rx>'9')&&rx!='-')rx=getchar();if(rx=='-')fh=-1,rx=getchar();while(rx>='0'&&rx<='9')ra*=10,ra+=rx-48,rx=getchar();return ra*fh;}


char Map[805][805];
int dp[805][805];
int n,m;

int xx[4] = {1,0,-1,0};
int yy[4] = {0,1,0,-1};

bool check(int x,int y)
{
    if(x<=n && x>0 && y<=m && y>0)return true;
    return false;
}

int main()
{
	//freopen("in.txt","r",stdin);
	//freopen("out.txt","w",stdout);
	//ios::sync_with_stdio(0);
	//cin.tie(0);
    n = read(), m = read();
	for(int i=1;i<=n;i++) scanf("%s",Map[i]+1);
	queue>q;
	for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            dp[i][j] = -1;
            if(Map[i][j]=='0')
            {
                dp[i][j] = 0;
                q.push(mp(i,j));
            }
        }
    }
    while(!q.empty())
    {
        int x = q.front().first;
        int y = q.front().second;
        q.pop();
        for(int i=0;i<4;i++)
        {
            int tx = x + xx[i];
            int ty = y + yy[i];
            if(check(tx,ty) && dp[tx][ty]==-1)
            {
                dp[tx][ty] = dp[x][y] + 1;
                q.push(mp(tx,ty));
            }
        }
    }
    for(int i=1;i<=n;i++)
    {
        for(int j=1;j<=m;j++)
        {
            printf("%d",dp[i][j]);
            if(j!=m)printf(" ");
        }
        printf("\n");
    }

	return 0;
}


你可能感兴趣的:(~~~~~acm~~~~~,——hiho一下——,BFS)