nyoj--92 图像有用区域(bfs)
2016-03-15 10:44
441 查看
nyoj 92
BFS遍历是一层一层的,对于每个当前正遍历的结点,如果它的邻接点(邻近的元素)为0,那就不作为扩展结点放入队列中,否则将其置为0并作为扩展节点放入队列。
这种方法需要把整个图像(矩阵)套在一个不是”0”的圈里,像装裱一副字画?
题解
此题实际上是要遍历”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; }
相关文章推荐
- Surrounded Regions
- Word Ladder, Gray Code
- UVA 11624
- HDU1495
- HDU2612 Find a way
- HDU1241 Oil Deposits
- Hdu2444二分图
- 最少步数BFS
- 转v_JULY_v的 BFS和DFS优先搜索算法
- 2015 寒假搜索专题 I - Meteor Shower(BFS)
- Same Tree
- E - Roads in the North
- DFS&BFS算法总结(1)
- Word Ladder I
- 图的BFS和DFS学习笔记
- [LeetCode] Binary Tree Level Order Traversal
- [LeetCode] Binary Tree Level Order Traversal II
- 关于BFS搜索的思想, 最简单的水题,不过深有体会啊。
- Word Ladder II
- Surrounded Regions