HDU 1312 矩阵中找出初始点的可达点数 简单bfs

本文介绍了一个使用C++实现的二维网格BFS(宽度优先搜索)算法,通过从指定起点开始遍历所有可达的空闲位置,并计算这些位置的数量。该算法适用于解决诸如迷宫寻路等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

#include <iostream>
#include <queue>
using namespace std;
const int N = 21;
int dir[4][2] = {{0,1}, {0, -1}, {1, 0}, {-1, 0}};
char a[N][N];
int cnt = 0;
int n, m;

struct node 
{
	int x, y;
};
void bfs(int x, int y)
{
	struct node cur, next;
	cur.x = x;
	cur.y = y;
	queue<node> q;
	q.push(cur);
	while(!q.empty())
	{
		cur = q.front();
		q.pop();
		for(int i = 0; i < 4; i++)
		{
			next.x = cur.x + dir[i][0];
			next.y = cur.y + dir[i][1];
			if(next.x >=0 && next.x < n && next.y >= 0 && next.y < m && a[next.x][next.y] == '.')
			{
				cnt++;
				q.push(next);
				a[next.x][next.y] = '#';
			}
		}
	}
}
int main()
{
	int x, y;
	while(cin >> m >> n, m || n )
	{
		for(int i = 0; i < n ; i++)
			scanf("%s", a+i);

		for(int i = 0; i < n; i++)
		{
			for(int j = 0; j < m; j++)
				if(a[i][j] == '@')
				{
					x = i;
					y = j;
					break;
				}
		}
		cnt = 1;
		bfs(x, y);
		cout << cnt << endl;
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值