实验十一 陆地数量

1. 题目来源:算法设计与问题求解第五章第二节

2.解题思路:

利用BFS的算法,遍历所有非零点,如果他们是互相连通就把他们的邻接点,push进入queue的,然后把st数组设置为true。

#include<iostream>
#include<queue>
using namespace std;
const int N = 1000;
char g[N][N];
bool st[N][N];
int n, m;
typedef pair<int, int> PII;//换名
int res = 0;//存储答案
int dx[] = { -1,0,1,0 };
int dy[] = { 0,1,0,-1 };
void bfs(int x, int y)//bfs的模板

{
	queue<PII> q;
	q.push({ x,y });
	st[x][y] = true;
	while (!q.empty())
	{
		auto t = q.front();
		q.pop();
		for (int i = 0; i < 4; i++)
		{
			int a = t.first + dx[i];
			int b = t.second + dy[i];
			if (a < 0 || b < 0 || a >= n || b >= m)continue;
			if (g[a][b] == '0')continue;
			if (st[a][b]) continue;
			st[a][b] = true;
			q.push({ a,b });
		}
	}

}
int main()
{
	cin >> n >> m;
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			cin >> g[i][j];
		}
	}
	
	for (int i = 0; i < n; i++)
	{
		for (int j = 0; j < m; j++)
		{
			if (g[i][j] != '0'&&!st[i][j])//遍历每个点,且这个点还没被push进入queue中
			{
				bfs(i, j);//将所有它的连接点的st数组全部置为true
				res++;//每多一个res++;
			}
		}
	}
	cout << res;
}

 3.运行代码

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值