BFS专题

题目:
在m*n矩阵中找出块的个数(块“相邻为1的点组合而成)
1 1 0 0
0 0 1 1
1 0 0 1
则相邻整体块数为 3
BFS实现:

#include <cstdio>
#include <iostream>
#include <queue>
#include <algorithm>
#include <string.h>
#include <cmath>

using namespace std;
const int maxn = 1000;
struct node
{
	int x,y;
}Node;
int m,n;
int X[4] = {-1,0,0,1};
int Y[4] = {0,1,-1,0};
int d[maxn][maxn];//用于存放迷宫数据
bool inq[maxn][maxn] ={false};

bool judge(int x,int y)
{
	//越界
		if(x > m || x < 0 || y < 0 || y > n) return false;
		//d[x][y]是0 或者是已经被访问过了
		if(d[x][y]==0 || inq[x][y] == true) return false;
		else return true;
}

void BFS(int x,int y)
{
	queue<node> q; //定义队列
	Node.x = x,Node.y = y;//当前节点(x,y)
	q.push(Node);//节点入队列
	inq[x][y] = true;//入队标记
	while(!q.empty())
	{
		node top =q.front(); //取出队首
		q.pop(); //弹出当前节点
		for(int i = 0; i < 4; i++) //循环4次得到四个相邻节点 判断 入队
		{
			int newx = top.x + X[i];
			int newy = top.y + Y[i];
			if(judge(newx,newy))
			{
				Node.x = newx;
				Node.y = newy;
				q.push(Node);
				inq[newx][newy] = true;
			}
		}
	}
}
int main()
{
	cin >> m >> n;
	for(int i = 0; i < m; i++)
	{
		for(int j = 0; j < n; j++)
		{
			cin >> d[i][j];
		}
	}

	int cont = 0;

	for(int i = 0; i < m; i++)
	{
		for(int j = 0; j < n; j++)
		{
			if(d[i][j] != 0 && !inq[i][j])
			{
				BFS(i,j);
				cont++;
			}
		}
	}
	cout << cont;
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

moumoumouwang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值