NYOJ 92 图像有用区域

来源:互联网 发布:淘宝关键词搜索查询 编辑:程序博客网 时间:2024/04/29 01:50

题目链接: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]);elseprintf("%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]);elseprintf("%d\n", map[i][j]);}}return 0;}