题目描述
编程计算由"1"围成的下列图形的面积。面积计算方法是统计"1"所围成的闭合曲线中"0"点的数目。如图所示,在10*10的二维数组中,"1"围住了15个点,因此面积为15。
提示:queue
输入
测试次数t
每组测试数据格式为:
数组大小m,n
一个由0和1组成的m*n的二维数组
输出
对每个二维数组,输出符号"1"围住的"0"的个数,即围成的面积。假设一定有1组成的闭合曲线,但不唯一。
输入输出样例
输入样例1 <-复制
2
10 10
0 0 0 0 0 0 0 0 0 0
0 0 0 0 1 1 1 0 0 0
0 0 0 0 1 0 0 1 0 0
0 0 0 0 0 1 0 0 1 0
0 0 1 0 0 0 1 0 1 0
0 1 0 1 0 1 0 0 1 0
0 1 0 0 1 1 0 1 1 0
0 0 1 0 0 0 0 1 0 0
0 0 0 1 1 1 1 1 0 0
0 0 0 0 0 0 0 0 0 0
5 8
0 1 1 0 0 1 1 0
1 0 1 0 1 0 0 1
0 1 0 1 0 0 1 0
0 1 0 0 1 1 1 0
0 0 0 0 0 0 0 0
输出样例1
74
5
AC代码
#include<iostream>
#include<queue>
using namespace std;
class map
{
int mat[50][50];
int m, n;
int xx[4] = { -1,0,1,0 };
int yy[4] = { 0,1,0,-1 };
queue<int>qx;
queue<int>qy;
public:
void set()
{
int i, j;
for (i = 0; i <= m + 1; i++)
for (j = 0; j <= n + 1; j++)
mat[i][j] = 0;
cin >> m >> n;
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
cin >> mat[i][j];
}
void dfs()
{
int i;
int x = 0, y = 0;
qx.push(0);
qy.push(0);
mat[0][0] = 1;
while (!qx.empty())
{
for (i = 0; i < 4; i++)
{
int nx = qx.front() + xx[i];
int ny = qy.front() + yy[i];
if (nx >= 0 && nx <= m+1 && ny >= 0 && ny <= n+1 && mat[nx][ny] == 0)
{
qx.push(nx);
qy.push(ny);
mat[nx][ny] = 1;
}
}
qx.pop();
qy.pop();
}
}
void show()
{
int i, j;
int shu = 0;
for (i = 1; i <= m; i++)
for (j = 1; j <= n; j++)
if (mat[i][j] == 0)
shu++;
cout << shu << endl;
}
};
int main()
{
int t;
cin >> t;
while (t--)
{
map tu;
tu.set();
tu.dfs();
tu.show();
}
}
(by 归忆)