hdu 1180 诡异的楼梯

本文详细解析了一种复杂的广度优先搜索(BFS)算法实现,该算法用于解决特定类型的迷宫问题,通过判断字符路径的有效性来寻找从起点到终点的最短路径。

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

点击打开链接

复杂bfs...

需要讨论开始为 | 还是 - 

#include"stdio.h"
#include"string.h"
#include"queue"
using namespace std;
int dir[4][2]={1,0,0,1,-1,0,0,-1};
int map[21][21];
char str[21][21];
int n,m,sx,sy;
struct node
{
	int x,y,step;
};
int judge(int x,int y)
{
	if(x>=0&&x<n&&y>=0&&y<m&&map[x][y]==0)
		return 1;
	return 0;
}
int fun(int x,int y,int xx,int yy,int step)
{
	if(xx>=0&&xx<n&&yy>=0&&y<m&&map[xx][yy]==0)
	{
		if(str[x][y]=='|')//开始为|
		{
			if(y==yy)//竖直过来
			{
				if(step%2==0)
					return 1;
				else
					return 0;
			}
			else//水平过来
			{
				if(step%2==1)
					return 1;
				else
					return 0;
			}
		}
		else//开始为-
		{
			if(yy==y)//竖直过来
			{
				if(step%2==1)
					return 1;
				else
					return 0;
			}
			else//水平过来
			{
				if(step%2==0)
					return 1;
				else
					return 0;
			}
		}
	}
	return 0;
}

void bfs()
{
	int x,xx,y,yy,i;
	node q,p;
	queue<node>Q;
	p.x=sx;
	p.y=sy;
	p.step=0;
	memset(map,0,sizeof(map));
	map[p.x][p.y]=1;
	Q.push(p);
	while(!Q.empty())
	{
		p=Q.front();
		Q.pop();
		for(i=0;i<4;i++)
		{
			x=p.x+dir[i][0];
			y=p.y+dir[i][1];
			if(str[x][y]=='.'||str[x][y]=='T')
			{
				if(judge(x,y))
				{
					map[x][y]=1;
					q.x=x;
					q.y=y;
					q.step=p.step+1;
					if(str[q.x][q.y]=='T')
					{
						printf("%d\n",q.step);
						return ;
					}
					Q.push(q);
				}
			}
			else if(str[x][y]=='|'||str[x][y]=='-')
			{
				xx=x+dir[i][0];
				yy=y+dir[i][1];
				if(str[xx][yy]!='*')
				{
					if(fun(x,y,xx,yy,p.step))
					{
						q.x=xx;
						q.y=yy;
						q.step=p.step+1;
						map[q.x][q.y]=1;
						if(str[xx][yy]=='T')
						{
							printf("%d\n",q.step);
							return ;
						}
						Q.push(q);
					}
					else if(judge(xx,yy))
					{
						if(map[xx][yy]==0)
						{
							q.x=p.x;
							q.y=p.y;
							q.step=p.step+1;
							map[q.x][q.y]=1;
							Q.push(q);
						}
					}
				}
			}
		}
	}
	printf("-1\n");
	return ;
}
int main()
{
	int i,j;
	while(scanf("%d%d",&n,&m)!=EOF)
	{
		for(i=0;i<n;i++)
			scanf("%s",str[i]);
		for(i=0;i<n;i++)
		{
			for(j=0;j<m;j++)
				if(str[i][j]=='S')
				{
					sx=i;sy=j;
				}
		}
		bfs();
	}
	return 0;
}
					


转载于:https://www.cnblogs.com/yyf573462811/archive/2012/07/24/6365396.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值