NYOJ-92 图像有用区域

图像有用区域

时间限制:3000 ms  |  内存限制:65535 KB

难度:4

描述

“ACKing”同学以前做一个图像处理的项目时,遇到了一个问题,他需要摘取出图片中某个黑色线圏成的区域以内的图片,现在请你来帮助他完成第一步,把黑色线圏外的区域全部变为黑色。

     

                图1                                                        图2 

输入

第一行输入测试数据的组数N(0<N<=6)
每组测试数据的第一行是两个个整数W,H分表表示图片的宽度和高度(3<=W<=1440,3<=H<=960)
随后的H行,每行有W个正整数,表示该点的像素值。(像素值都在0到255之间,0表示黑色,255表示白色)

输出

以矩阵形式输出把黑色框之外的区域变黑之后的图像中各点的像素值。

样例输入

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

样例输出

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

已知黑线各处不会出现交叉(如图2),并且,除了黑线上的点外,图像中没有纯黑色(即像素为0的点)。

#include<cstdio>
#include<cstring>
#include<queue>
using namespace std;
int w,h;
int map[1445][965];
int d[4][2]= {1,0,-1,0,0,1,0,-1};
//四个方向 

struct node
{
	int x,y;
};

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+d[i][0];
			t2.y=t1.y+d[i][1];
			if(t2.x<0||t2.x >w+1||t2.y<0||t2.y>h+1||map[t2.x][t2.y]==0)
			//边界判定,注意最后一个判定条件的顺序不能放在前面,否则可能会溢出
			//而且必须将加的一圈1也放进搜索里,这样才能保证不遗漏 
				continue;
			map[t2.x][t2.y]=0;
			q.push(t2);
		}
	}
}

int main()
{
	int T;
	scanf("%d",&T);
	while(T--)
	{
		memset(map,-1,sizeof(map));
		scanf("%d%d",&w,&h);

		for(int i=0; i<=h; i++)
			map[0][i]=map[w+1][i]=1;
		for(int i=0; i<=w; i++)
			map[i][0]=map[i][h+1]=1;
//在图像的外围加上一圈非黑(1)。
//这样就能保证图像的一周都可以被遍历到,不会遗漏 

		for(int i=1; i<=w; i++)
		{
			for(int j=1; j<=h; j++)
			{
				scanf("%d",&map[i][j]);
			}
		}
		bfs(0,0);
		for(int i=1; i<=w; i++)
		{
			for(int j=1; j<=h; j++)
			{
				printf("%d",map[i][j]);
				if(j<h)
					printf(" ");
			}
			printf("\n");
		}
		printf("\n");

	}
}

猜你喜欢

转载自blog.csdn.net/yxy602843889/article/details/81907858