题目描述
编程计算由"1"围成的下列图形的面积。面积计算方法是统计"1"所围成的闭合曲线中"0"点的数目。如图所示,在10*10的二维数组中,"1"围住了15个点,因此面积为15。
输入
测试次数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
输入样例2
15
5
代码
// 10.16 B. DS图—图非0面积
#include<iostream>
using namespace std;
#define MAX 100
class Matrix {
int m, n;
int mat[MAX][MAX];
public:
Matrix(int m,int n) {
this->m = m;
this->n = n;
for (int i = 0; i < m + 2; i++) {
for (int j = 0; j < n + 2; j++) {
mat[i][j] = 0;//初始化
}
}
}
void input_Mat() {
for (int i = 1; i < m + 1; i++) {
for (int j = 1; j < n + 1; j++) {
cin >> mat[i][j];//输入矩阵
}
}
}
void go_Mat(int x,int y) {//起点
//基本思想:从外到内,包围式把外面的0变成1
//向上走,x-1,边界为-1
if (x - 1 != -1 && mat[x - 1][y] == 0) {
mat[x - 1][y] = 1;
go_Mat(x - 1, y);
}
//向下走,x+1,边界为m+2
if (x + 1 != m+2 && mat[x + 1][y] == 0) {
mat[x + 1][y] = 1;
go_Mat(x + 1, y);
}
//向左走,y-1,边界为-1
if (y - 1 != -1 && mat[x][y-1] == 0) {
mat[x][y-1] = 1;
go_Mat(x, y-1);
}
//向右走,y+1,边界为n+2
if (y + 1 != -1 && mat[x][y+1] == 0) {
mat[x][y+1] = 1;
go_Mat(x, y+1);
}
}
void display() {
int area = 0;
for (int i = 1; i < m+1; i++)
for (int j = 1; j < n+1; j++)
if (mat[i][j] == 0)
area++;
cout << area << endl;
}
};
int main() {
int t;
cin >> t;
while (t--) {
int m, n;
cin >> m >> n;
Matrix mat(m, n);
mat.input_Mat();
mat.go_Mat(0,0);
mat.display();
}
}