NYOJ 92 图像有用区域

题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=92

解题思路:

很简单的一个广搜题,思路也很简单,只需要在图外加一圈1,从左上角开始广搜即可。

把坐标入队即可。

本道题最蛋疼的就是先输入宽,后输入的高。。。这点让我wrong了N久~大哭


代码如下:

#include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<algorithm> using namespace std; int map[1000][1500]; int row, col; int dir[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}}; //上下左右 queue<int>que; void BFS(int i, int j) { int x, y; int a, b; que.push(i); que.push(j); while(!que.empty()) { x = que.front(); que.pop(); y = que.front(); que.pop(); for(int i = 0; i < 4; ++i) { a = x + dir[i][0]; b = y + dir[i][1]; if(a < 0 || b < 0 || a > row + 1 || b > col + 1) //超边界 continue; if(map[a][b] == 0) continue; map[a][b] = 0; que.push(a); que.push(b); } } } int main() { int ncase; scanf("%d", &ncase); while(ncase--) { while(!que.empty()) que.pop(); for(int i = 0; i < 1000; ++i) for(int j = 0; j < 1500; ++j) map[i][j] = 1; scanf("%d%d", &col, &row); for(int i = 1; i <= row; ++i) for(int j = 1; j <= col; ++j) scanf("%d", &map[i][j]); BFS(0, 0); for(int i = 1; i <= row; ++i) for(int j = 1; j <= col; ++j) { if(j != col) printf("%d ", map[i][j]); else printf("%d\n", map[i][j]); } } return 0; }

优化的一点点就是在外面加一圈1,只需要2次for循环。。。

#include<iostream> #include<cstdio> #include<cstring> #include<queue> #include<algorithm> using namespace std; int map[1000][1500]; int row, col; int dir[4][2] = {{0, 1}, {0, -1}, {-1, 0}, {1, 0}}; //上下左右 queue<int>que; void BFS(int i, int j) { int x, y; int a, b; que.push(i); que.push(j); while(!que.empty()) { x = que.front(); que.pop(); y = que.front(); que.pop(); for(int i = 0; i < 4; ++i) { a = x + dir[i][0]; b = y + dir[i][1]; if(a < 0 || b < 0 || a > row + 1 || b > col + 1) //超边界 continue; if(map[a][b] == 0) continue; map[a][b] = 0; que.push(a); que.push(b); } } } int main() { int ncase; scanf("%d", &ncase); while(ncase--) { while(!que.empty()) que.pop(); //memset(map, -1, sizeof(map)); scanf("%d%d", &col, &row); for(int i = 0; i <= col + 1; ++i) { map[0][i] = 1; map[row + 1][i] = 1; } for(int i = 0; i <= row + 1; ++i) { map[i][0] = 1; map[i][col + 1] = 1; } for(int i = 1; i <= row; ++i) for(int j = 1; j <= col; ++j) scanf("%d", &map[i][j]); BFS(0, 0); for(int i = 1; i <= row; ++i) for(int j = 1; j <= col; ++j) { if(j != col) printf("%d ", map[i][j]); else printf("%d\n", map[i][j]); } } return 0; }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值