poj1979 简单bfs

本文介绍了一种使用广度优先搜索(BFS)算法来解决迷宫中可达区域的问题。通过给定一个由#.和@组成的矩形地图,算法能够找出从起点@出发能够到达的所有位置,并统计这些位置的数量。

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

题意:

就是给一个矩形,由.和#还有@组成,#不能走,然后一个人站在@处,问这个人最多可以走的位置有哪些。


一个简单的bfs,然后看vis数组里面有多少个位置被标记就可以了。


#include <iostream>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>

using namespace std;

int const maxn = 25;
char str[maxn][maxn];
int vis[maxn][maxn];
int w,h;
int ex,ey;

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

struct  node
{
	int x,y;
	int step ; 
};

void bfs()
{
	queue<node> q;
	node cur , next;
	cur.x = ex , cur.y = ey;
	cur.step = 0;
	vis[ex][ey]=1;
	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];
			next.step = cur.step + 1;
			//cout<<next.x<<" "<<next.y<<" "<<next.step<<endl;
			if(next.x>=0&&next.x<h&&next.y>=0&&next.y<w
				&&!vis[next.x][next.y]&&str[next.x][next.y]!='#')
			{
				//cout<<next.step<<endl;
				q.push(next);
				vis[next.x][next.y] = 1;
			}
		}
	}
}

int main()
{
	while(scanf("%d%d",&w,&h)&&(w||h))
	{
		for (int i = 0 ; i < h ; i++)
		{
			scanf("%s",str[i]);
			for(int j = 0 ; j < w ; j++)
			{
				if(str[i][j]=='@')
				{
					ex = i; 
					ey = j;
				}
			}
		}
		memset(vis,0,sizeof(vis));
		int ans = 0;
		bfs() ;
		for(int i = 0 ; i < h ; i++)
		{
			for(int j = 0 ; j < w ; j++)
			{
				if(vis[i][j])ans++;
			}
		}
		printf("%d\n",ans);
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值