• 矩阵距离


    题目链接

    题意:就是求每个点到最近的1的距离,但距离是|xi-x|+|yi-y|。

    思路:将每个是1的点BFS全图,想到了就是很水的BFS。

    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #include<vector>
    #include<map>
    #include<queue>
    #define ll long long
    using namespace std;
    const int dx[4]={0,0,-1,1},dy[4]={1,-1,0,0};
    int n,m;
    char a[1010][1010];
    int b[1010][1010];
    queue<pair<int,int> > q;
    int main()
    {
        cin>>n>>m;
        for(int i=1;i<=n;i++)
            scanf("%s",a[i]+1);
            memset(b,-1,sizeof(b));
        for(int i=1;i<=n;i++)
            for(int j=1;j<=m;j++)
            if(a[i][j]=='1') q.push(make_pair(i,j)),b[i][j]=0;
        
        while(q.size())
        {    pair<int,int> now =q.front();
        
            q.pop();
            for(int i=0;i<4;i++)
        {    pair<int,int> next(now.first+dx[i],now.second+dy[i]);
            if(next.first<1||next.second<1||next.first>n||next.second>m)
            continue;
            if(b[next.first][next.second]==-1)
        {    b[next.first][next.second]=b[now.first][now.second]+1;
            q.push(next);} 
            
            }
        }
        for(int i=1;i<=n;i++)
        {
            for(int j=1;j<=m;j++)
                cout<<b[i][j]<<" ";
            cout<<endl;
        }
    }
  • 相关阅读:
    JQuery
    Ubuntu18.04
    Ubuntu18.04
    Ubuntu18.04
    Ubuntu18.04
    Cordova
    Android
    Android
    Delphi
    postgresql之 drop & delete & truncate
  • 原文地址:https://www.cnblogs.com/2462478392Lee/p/11291434.html
Copyright © 2020-2023  润新知