问题描述:
图像有用区域
时间限制:3000 ms | 内存限制:65535 KB
难度:4
描述
“ACKing”同学以前做一个图像处理的项目时,遇到了一个问题,他需要摘取出图片中某个黑色线圏成的区域以内的图片,现在请你来帮助他完成第一步,把黑色线圏外的区域全部变为黑色。
已知黑线各处不会出现交叉(如图2),并且,除了黑线上的点外,图像中没有纯黑色(即像素为0的点)。
输入
第一行输入测试数据的组数N(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
分析:
题目一看就知道要用到广搜,那么从哪里开始搜呢?原先我的想法还是从四个角开始搜,但是代码没有过。仔细想了想有特殊情况可以使他不成立。后来又想了想,在最外层加一圈1,然后从0,0开始广搜即可;
线可以是斜着的所以搜索时只用搜上下左右是个方向。
注意:以前我写这题的话一定会用一个point结构体,然后让结构体入队列,这次是看到了其他的代码,可以直接将x,y一起入队列,再一起取出来就可以了。
AC代码:
#include <iostream>
#include <queue>
using namespace std;
const int maxn=1500;
int map[maxn][maxn];
int way[4][2]={{1,0},{-1,0},{0,1},{0,-1}};
queue<int> q;
int w,h;
void bfs(int i,int j)
{
int nowx,nowy;
int nextx,nexty;
q.push(i);
q.push(j);
map[i][j]=0;
while(!q.empty())
{
nowx=q.front();
q.pop();
nowy=q.front();
q.pop();
for(int i=0;i<4;i++)
{
nextx=nowx+way[i][0];
nexty=nowy+way[i][1];
if(nextx>=0 && nextx<=h+1 && nexty>=0 && nexty<=w+1 && map[nextx][nexty]>0)
{
map[nextx][nexty]=0;
q.push(nextx);
q.push(nexty);
}
}
}
}
int main()
{
int T;
cin>>T;
while(T--)
{
int i,j;
while(!q.empty())
q.pop();
cin>>w>>h;
for( i=1;i<=h;i++)
{
for( j=1;j<=w;j++)
{
cin>>map[i][j];
}
}
for(i=0;i<=w+1;i++)
{
map[0][i]=1;
map[h+1][i]=1;
}
for(i=0;i<=h+1;i++)
{
map[i][0]=1;
map[i][w+1]=1;
}
bfs(0,0);
for(i=1;i<=h;i++)
{
for(j=1;j<=w;j++)
{
cout<<map[i][j]<<" ";
}
cout<<endl;
}
}
return 0;
}