您的位置:首页 > 其它

nyoj--92 图像有用区域(bfs)

2016-03-15 10:44 441 查看
nyoj 92

题解

此题实际上是要遍历”0”圈以外的数,把它们置为0。

BFS遍历是一层一层的,对于每个当前正遍历的结点,如果它的邻接点(邻近的元素)为0,那就不作为扩展结点放入队列中,否则将其置为0并作为扩展节点放入队列。

这种方法需要把整个图像(矩阵)套在一个不是”0”的圈里,像装裱一副字画?

#include <iostream>
#include <cstdio>
#include <queue>
#include <fstream>
#include <algorithm>
using namespace std;

typedef pair<int, int> pii;
const int maxw = 1445;
const int maxh = 965;
int   g[maxh][maxw];
int   w, h, t;
int   dir[4][2] = { {0, 1}, {-1, 0}, {1, 0}, {0, -1} };

void bfs()
{
queue<pii> Q;
Q.push(make_pair(0, 0));
while(!Q.empty())
{
pii p = Q.front();
Q.pop();
int x = p.first, y = p.second;
for(int i = 0; i < 4; ++i)
{
int newx = x + dir[i][0], newy = y + dir[i][1];
if(newx < 0 || newx > h + 1 || newy < 0 || newy > w + 1 || g[newx][newy] == 0) continue;
g[newx][newy] = 0;
Q.push(make_pair(newx, newy));
}
}
}

int main()
{
#ifdef LOCAL
fstream cin("data.in");
#endif // LOCAL

ios::sync_with_stdio(false);
cin.tie(0);
for(cin >> t; t--; )
{
cin >> w >> h;
for(int i = 0; i < maxh; ++i) fill(*(g + i), *(g + i) + maxw, 1);

for(int i = 1; i <= h; ++i)
{
for(int j = 1; j <= w; ++j)
{
cin >> g[i][j];
}
}
bfs();
for(int i = 1; i <= h; ++i)
{
for(int j = 1; j <= w; ++j)
{
cout << g[i][j] << " ";
}
cout << endl;
}
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nyoj bfs easy+