• 0x20搜索(0x25广度优先搜索)例题2:矩阵距离(题解)


    题意

    题目链接

    【题意】
     给定一个N行M列的01矩阵A,A[i][j] 与 A[k][l] 之间的曼哈顿距离定义为:
    dist(A[i][j],A[k][l])=|i−k|+|j−l|
    输出一个N行M列的整数矩阵B,其中:
    B[i][j]=min1≤x≤N,1≤y≤M,A[x][y]=dist(A[i][j],A[x][y])
    
    【输入格式】
     第一行两个整数n,m。
     接下来一个N行M列的01矩阵,数字之间没有空格。
    
     【输出格式】
     一个N行M列的矩阵B,相邻两个整数之间用一个空格隔开。
     【数据范围】
    1≤N,M≤1000
    【输入样例】
    3 4
     0001
     0011
     0110
    【输出样例】
    3 2 1 0
     2 1 0 0
     1 0 0 1
    

    题解

    SB题吗。

    对于每个1都踢入队列,然后乱找,不就行了?

    #include<cstdio>
    #include<cstring>
    #define  N  1100
    #define  NN  1100000
    using  namespace  std;
    struct  node
    {
    	int  x,y;
    }list[NN];int  head,tail;
    int  dis[N][N],a[N][N];/*定义为B数组+1*/
    int  n,m;
    char  st[N];
    int  dx[]={0,-1,0,1};
    int  dy[]={-1,0,1,0};
    int  main()
    {
    	head=1;
    	scanf("%d%d",&n,&m);
    	for(int  i=1;i<=n;i++)
    	{
    		scanf("%s",st+1);
    		for(int  j=1;j<=m;j++)
    		{
    			a[i][j]=(st[j]=='1');
    			if(a[i][j]==1)
    			{
    				dis[i][j]=1;
    				list[++tail].x=i;list[tail].y=j;
    			}
    		}
    	}
    	while(head<=tail)
    	{
    		node  pre=list[head++];
    		for(int  i=0;i<=3;i++)
    		{
    			node  now;
    			now.x=pre.x+dx[i];now.y=pre.y+dy[i];
    			if(1<=now.x  &&  now.x<=n  &&  now.y>=1  &&  now.y<=m  &&  !dis[now.x][now.y])
    			{
    				dis[now.x][now.y]=dis[pre.x][pre.y]+1;
    				list[++tail]=now;
    			}
    		}
    	}
    	for(int  i=1;i<=n;i++)
    	{
    		for(int  j=1;j<m;j++)printf("%d ",dis[i][j]-1);
    		printf("%d
    ",dis[i][m]-1);
    	}
    	return  0;
    }
    
  • 相关阅读:
    JZOJ Contest2633 总结
    6813. 【2020.10.05提高组模拟】送信
    HDU 1506 最大子矩形
    2020.10.07【NOIP提高A组】模拟 总结
    6815. 【2020.10.06提高组模拟】树的重心
    2020.10.06【NOIP提高A组】模拟 总结
    2020.10.05【NOIP提高A组】模拟 总结
    gmoj 3976. 【NOI2015模拟1.17】⑨
    2020.09.26【省选组】模拟 总结
    2020.09.19【省选组】模拟 总结
  • 原文地址:https://www.cnblogs.com/zhangjianjunab/p/11714646.html
Copyright © 2020-2023  润新知