nyoj92 图像有用区间(dfs)




//广搜
#include<stdio.h>
#include<string.h>
#include<queue>
using namespace std;
struct node{
	int x;
	int y;
};
int w,h;
int mat[961][1441];
int xx[4]={0,0,-1,1};
int yy[4]={1,-1,0,0};
void bfs(int a,int b){
	queue<node>q;
	node t1,t2;
	t1.x =a;
	t1.y =b;
	q.push(t1);
	while(!q.empty()){
		t1=q.front();
		q.pop();
		for(int i=0;i<4;i++){
			t2.x =t1.x +xx[i];
			t2.y =t1.y +yy[i];
			if(t2.x <0||t2.y<0||t2.x>h+1||t2.y>w+1||mat[t2.x][t2.y]==0)
			continue;
			mat[t2.x][t2.y]=0;
			q.push(t2);
		}
	}
}
int main()
{
	int n;
	scanf("%d",&n);
	while(n--){
		int a;
		scanf("%d%d",&w,&h);
		memset(mat,1,sizeof(mat));
		for(int i=1;i<=h;i++)
		for(int j=1;j<=w;j++){
			scanf("%d",&a);
			mat[i][j]=a;
		}
		bfs(0,0);
		for(int i=1;i<=h;i++){
		for(int j=1;j<=w;j++){
			if(j==w)
			printf("%d\n",mat[i][j]);
			else 
			printf("%d ",mat[i][j]);
		}
		}
	}
	return 0;
}

//深搜
# include<stdio.h>
# include<string.h>
int a[1000][1445],w,h;
void dfs(int c1,int c2)
{
	if(a[c1][c2]&&c1>=0&&c2>=0&&c1<=h+1&&c2<=w+1)
	{
		a[c1][c2]=0;
	dfs(c1,c2+1);
	dfs(c1+1,c2);
	dfs(c1-1,c2);
	dfs(c1,c2-1);
		}	
}
int main(){
int t;	
	scanf("%d",&t);
	while(t--)
	{  memset(a,1,sizeof(a));//在数组外在 
		int i,j;
		scanf("%d%d",&w,&h);
		for(i=1;i<=h;i++)
		for(j=1;j<=w;j++)
		scanf("%d",&a[i][j]);
		
				dfs(0,0);
		
		for(i=1;i<=h;i++){	
		for(j=1;j<=w;j++)
		
			printf("%d ",a[i][j]);
			printf("\n");
		}
	}	
return 0;	
} 



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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值