题目链接:here~~
首先有一个比较明确的思路:对矩形四周的每个点向周围进行搜索,遇到0则停止,把不为0的数变为0。
看数据量的大小用深搜的话肯定栈溢出RTE,所以选择用广搜!代码如下:
#include <iostream>
#include <queue>
#include <cstdio>
#include <string.h>
using namespace std;
int map[970][1450];
struct point
{
int x, y;
}a, b;
int dx[4]={1, -1, 0, 0};
int dy[4]={0, 0, 1, -1};
void bfs(int i, int j)
{
queue<point> p;
a.x=i;
a.y=j;
p.push(a);
while (!p.empty())
{
a=p.front();
p.pop();
for (i=1; i<=4; i++)
{
b.x=a.x+dx[i];
b.y=a.y+dy[i];
if (map[b.x][b.y]!=0)
{
map[b.x][b.y]=0;
p.push(b);
}
}
}
}
int main()
{
int N, n, m, i, j;
// freopen("in.txt", "r", stdin);
scanf("%d", &N);
while (N--)
{
memset(map, 0, sizeof(map));
scanf("%d%d", &n, &m);
for (i=1; i<=m; i++)
for (j=1; j<=n; j++)
scanf("%d", &map[i][j]);
for (i=1; i<=n; i++)//第1行和第m行
{
if (map[1][i]!=0)//不为零则搜索
bfs(1, i);
if (map[m][i]!=0)
bfs(m, i);
}
for (i=1; i<=m; i++)//第1列和第n列
{
if (map[i][1]!=0)
bfs(i, 1);
if (map[i][n]!=0)
bfs(i, n);
}
for (i=1; i<=m; i++)
{
printf("%d", map[i][1]);
for (j=2; j<=n; j++)
printf(" %d", map[i][j]);
printf("\n");
}
}
return 0;
}