AcWing 173. 矩阵距离

题目传送门


今天考试的t1

某位菜鸡考的时候只做了20分

题意:对于给定的01矩阵,求出矩阵上所有点到其最近的1的曼哈顿距离。

思路:

考试的时候看完题,嗯?广搜水题?然后几分钟就打完了那段20分的拙劣代码。最初始的想法:对于每个0点,跑一边bfs即可,时间复杂度O(\(n^2\)),打完觉得不太对,可能会挂,然后改成了对于每个1点,用bfs去遍历更新其他点的最小值,然而时间复杂度似乎没差,自己测的数据还是会T,但抱着侥幸的心理想着应该不会挂太多的点吧……然后就20分了。

[正确的解法]合理利用bfs的层次单调性,对于一个无向无边权值的矩阵,bfs每次更新的一定是当前能更新到的最短距离,所以只需要将所有的1的点放入队列中,然后跑bfs即可。。。(这么简单还想不到,我真是菜啊


Code:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
//Mystery_Sky
//
#define M 1000101
#define INF 0x3f3f3f3f
#define ll long long
inline int read()
{
    int x=0, f=1;char c=getchar();
    while(c<'0'||c>'9') {if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}
int n, m;
int map[2000][2000];
int ans[1500][1500];
struct node{
    int x, y, step;
};
int dx[] = {0, 0, 1, -1};
int dy[] = {1, -1, 0, 0};
queue <node> Q;
inline void bfs()
{
    while(!Q.empty()) {
        node top = Q.front();
        Q.pop();
        for(int i = 0; i <= 3; i++) {
            int xx = top.x + dx[i];
            int yy = top.y + dy[i];
            if(xx <= 0 || xx > n || yy <= 0 || yy > m) continue;
            if(ans[xx][yy] == INF) ans[xx][yy] = top.step + 1, Q.push((node) {xx, yy, top.step + 1}); 
        }
    }
}

int main() {
    n = read(), m = read(); 
    memset(ans, INF, sizeof(ans));
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= m; j++) {
            scanf("%1d", &map[i][j]);
            if(map[i][j] == 1) ans[i][j] = 0, Q.push((node){i, j, 0}) ;
        }
    }
    bfs();
    for(int i = 1; i <= n; i++) {
        for(int j = 1; j <= m; j++) {
            printf("%d ", ans[i][j]);
        }
        putchar(10);
    }
    return 0;
} 

转载于:https://www.cnblogs.com/Benjamin-cpp/p/11380159.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值