寒假算法训练4-B(从四条边的每一个点进行dfs)

在这里插入图片描述
Sample Input
1
5 5
100 253 214 146 120
123 0 0 0 0
54 0 33 47 0
255 0 0 78 0
14 11 0 0 0
Sample Output
0 0 0 0 0
0 0 0 0 0
0 0 33 47 0
0 0 0 78 0
0 0 0 0 0

#include <bits/stdc++.h>
using namespace std;
const int maxw=1500,maxh=1500;
int dis[4][2]={1,0,-1,0,0,1,0,-1};
int h,w,t;
int a[maxh][maxw];

void dfs(int x,int y)
{
    a[x][y]=0;
    for(int i=0;i<4;i++)
    {
        int tx=x+dis[i][0];
        int ty=y+dis[i][1];
        if(tx>=0 && ty>=0 && tx<h && ty<w && a[tx][ty]!=0) dfs(tx,ty);
    }
}
int main()
{
    cin>>t;
    while(t--)
    {
        memset(a,-1,sizeof(a));
        cin>>w>>h;
        for(int i=0;i<h;i++)
            for(int j=0;j<w;j++) cin>>a[i][j];
        for(int i=0;i<w;i++)
        {
            if(a[0][i]!=0) dfs(0,i);
            if(a[0][h-1]!=0) dfs(0,h-1);
        }
        for(int i=0;i<h;i++)
        {
            if(a[i][0]!=0) dfs(i,0);
            if(a[i][w-1]!=0) dfs(i,w-1);
        }
        for(int i=0;i<h;i++)
        {
            for(int j=0;j<w;j++) cout<<a[i][j]<<" ";
            cout<<endl;
        }
    }
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值