运用广度优先搜索实现统计岛屿数量

广度搜索简单介绍= =//

类似于在一块地上倒一桶水,看看水所能漫延到的所有地方(拙劣见解)哈哈哈= =||

也就是说找到与某个点有联系的所有的点//

广搜在统计岛屿数量的原理(拙劣)///

我们简单地把海洋标记成0,把陆地标记成正整数

emmmmm。。。

首先用一个book数组来标记岛屿的所有点,没走过的点标记0,走过的点标记为1

然后对地图的每个点进行遍历

当遇到一块没走过的陆地时,我们就使用广搜把这块陆地全部标记,然后继续遍历地图即可,,

直到遍历了地图的所有点,我们就终止程序。= =/

实现///

我们假设地图最大是50×50的,

	struct node que[2501];       //队列     //最多有2500个点
	int head=1, tail=1;            //队列的初始化
	int a[51][51];                //用于记录地图
	int book[51][51] = { 0 };                //标记地图的数组

我们用一个二维数组记录每一步可以走的方向(右下左上)顺时针方向

	int next[4][2] = {
		{0,1},{1,0},{0,-1},{-1,0}
	};

对地图的每个点进行遍历,

并通过广搜标记所有与当前点有联系的点///

	for(int i=1;i<=n;++i)
		for (int j = 1; j <= m; ++j)
		{
			//确认降落坐标
			if (a[i][j] == 0||book[i][j]==1)        //海洋或者已经走过
				continue;
			else if(a[i][j]!=0&&book[i][j]==0)       //陆地且没走过/
			{//那么就把这个点当作我们广搜的源点
				startx = i;
				starty = j;
			}
             //入队
			que[tail].x = startx;
			que[tail].y = starty;
			++tail,++sum;			//sum记录岛屿数量
			book[startx][starty] = 1;        //标记源点
            //通过广搜标记所有与源点有联系的点
			while (head < tail)
			{
				for (int k = 0; k < 4; k++)
				{
					tx = que[head].x + next[k][0];
					ty = que[head].y + next[k][1];
					if (tx<1 || ty<1 || tx>n || ty>m)
						continue;
					if (a[tx][ty] > 0 && book[tx][ty] == 0)
					{
						book[tx][ty] = 1;
						que[tail].x = tx;
						que[tail].y = ty;
						++tail;
					}
				}
                //这一步一定要有,代表当前点已经使用过了,让它出队休息一下ba///
				++head;		//扩展
			}
		}

总体代码实现

#include <iostream>
using namespace std;
struct node {
	int x, y;
};
int main()
{
	ios::sync_with_stdio(false);
	struct node que[2501];
	int head=1, tail=1;
	int a[51][51];
	int book[51][51] = { 0 };
	int sum = 0, n, m, startx, starty, tx, ty;
	int next[4][2] = {
		{0,1},{1,0},{0,-1},{-1,0}
	};
	//读入n行m列
	cin >> n >> m;
	//读入地图		0表示海洋
	for (int i = 1; i <= n; ++i)
		for (int j = 1; j <= m; ++j)
			cin >> a[i][j];
	for(int i=1;i<=n;++i)
		for (int j = 1; j <= m; ++j)
		{
			//确认降落坐标
			if (a[i][j] == 0||book[i][j]==1)
				continue;
			else if(a[i][j]!=0&&book[i][j]==0)
			{
				startx = i;
				starty = j;
			}
			que[tail].x = startx;
			que[tail].y = starty;
			++tail,++sum;			//sum记录岛屿数量
			book[startx][starty] = 1;
			while (head < tail)
			{
				for (int k = 0; k < 4; k++)
				{
					tx = que[head].x + next[k][0];
					ty = que[head].y + next[k][1];
					if (tx<1 || ty<1 || tx>n || ty>m)
						continue;
					if (a[tx][ty] > 0 && book[tx][ty] == 0)
					{
						book[tx][ty] = 1;
						que[tail].x = tx;
						que[tail].y = ty;
						++tail;
					}
				}
				++head;		//扩展
			}
		}
	cout << "有 " << sum << " 个小岛..\n";
	system("pause");
	return 0;
}

再见 = =///

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值