您的位置:首页 > 其它

NYOJ 92 图像有用区域 (经典的 bfs)

2016-03-07 20:34 295 查看
图像有用区域

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

难度:4

描述

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




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

输入

第一行输入测试数据的组数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

代码:bfs:

#include <iostream>
#include <queue>

using namespace std;

struct point
{
int x;
int y;
};

int w, h;
int map[970][1450];
int dir[4][2] = {-1, 0, 0, 1, 1, 0, 0, -1};

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

int main()
{
int T;
cin >> T;
while(T--)
{
cin >> w >> h;
//在图像的一圈加上 1,即令其为非黑即可,
//这样就能保证图像的一周都可以被遍历一遍,不会遗漏
for(int i = 0; i <= h; ++i)
map[i][0] = map[i][w + 1] = 1;
for(int j = 0; j <= w; ++j)
map[0][j] = map[h + 1][j] = 1;

for(int i = 1; i <= h; ++i)
for(int j = 1; j <= w; ++j)
cin >> map[i][j];
BFS(0, 0);
for(int i = 1; i <= h; ++i)
for(int j = 1; j <= w; ++j)
{
if(j == w)
cout << map[i][j] << endl;
else
cout << map[i][j] << ' ';
}
}
return 0;
}


别人的bfs:

#include<iostream>
#include<queue>
using namespace std;

const int W =  1500;
const int H = 1000;
int mp[H][W];	//之前写成mp[W][H]一直WA = =!
struct Node
{
int si,sj;
};
queue<Node> q;
int dir[4][2] = {{-1,0},{0,1},{1,0},{0,-1}};
int w,h;

void bfs(int si,int sj)
{
int di,i,j;
Node p;
Node tmp;
p.si = si,	p.sj = sj;
q.push(p);
while(!q.empty())
{
p = q.front();
q.pop();
for(di=0;di<4;di++)
{
i = p.si + dir[di][0];
j = p.sj + dir[di][1];
if (i>=0 && i<=h+1 &&j>=0 && j<=w+1 && mp[i][j])
{
tmp.si = i,	tmp.sj = j;
q.push(tmp);
mp[i][j] = 0;
}
}
}
}
int main()
{
void Out();
void SetBord();
int t;
cin>>t;
while(t--)
{
cin>>w>>h;
int i,j;
for (i=1;i<=h;i++)
for(j=1;j<=w;j++)
cin>>mp[i][j];
SetBord();	//加边处理
bfs(0,0);	//由于外面加了一层边,所以从0,0开始可以搜到边界的所有。
Out();	//输出
}
return 0;
}

void Out()
{
int i,j;
for(i=1;i<=h;i++)
{
for(j=1;j<=w;j++)
{
cout<<(j==1?"":" ")<<mp[i][j];
}
cout<<endl;
}
}
void SetBord()
{
int i;
for(i=0;i<=w+1;i++)mp[0][i] = 1;
for(i=0;i<=h+1;i++)mp[i][0] = 1;
for(i=0;i<=w+1;i++)mp[h+1][i] = 1;
for(i=0;i<=h+1;i++)mp[i][w+1] = 1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: