B. DS图—图非0面积

题目描述

编程计算由"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();
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值