hdu1180诡异的楼梯(bfs)

最近做题缺乏手感,找一道bfs练一练
题目链接
这种题目属于最简单的那种bfs,需要注意的是遇到楼梯时的处理,如果不满足通过楼梯的条件,则需要退回到原位置等待,此时原位置也需要入队。

#include <bits/stdc++.h>
using namespace std;
char maps[22][22];
bool st[22][22];
int n,m;
int dir[][2] = {{-1,0},{1,0},{0,-1},{0,1}};
struct node{
	int x,y,step;
};
node s,t;
bool check(node a)
{
	int x=a.x;
	int y=a.y;
	if(x<0||x>=n||y<0||y>=m||st[x][y]||maps[x][y]=='*')
        return false;
    return true;
}
int bfs()
{
	memset(st,false,sizeof st);
	queue<node> q;
	st[s.x][s.y]=true;
	q.push(s);
	while(q.size())
	{
		node a=q.front();
		q.pop();
		if(a.x==t.x&&a.y==t.y)
		{
			return a.step;
		}
		node nxt;
		for(int i=0;i<4;i++)
		{
			nxt.x=a.x+dir[i][0];
			nxt.y=a.y+dir[i][1];
			nxt.step=a.step+1;
			if(!check(nxt))
			{
				continue;
			}
			if(maps[nxt.x][nxt.y]=='.')
			{
				st[nxt.x][nxt.y]=true;
				q.push(nxt);
				continue;
			}
			if(maps[nxt.x][nxt.y]=='|')
			{
				if(((i==0||i==1)&&(nxt.step&1))||((i==2||i==3)&&!(nxt.step&1)))
				{
					nxt.x+=dir[i][0];
					nxt.y+=dir[i][1];
					if(check(nxt))
					{
						st[nxt.x][nxt.y]=true;
						q.push(nxt);
					}
				}
				else 
				{
					nxt.x=a.x;
					nxt.y=a.y;
					q.push(nxt);
				}
			}
			if(maps[nxt.x][nxt.y]=='-')
			{
				if(((i==0||i==1)&&!(nxt.step&1))||((i==2||i==3)&&(nxt.step&1)))
				{
					nxt.x+=dir[i][0];
					nxt.y+=dir[i][1];
					if(check(nxt))
					{
						st[nxt.x][nxt.y]=true;
						q.push(nxt);
					}
				}
				else 
				{
					nxt.x=a.x;
					nxt.y=a.y;
					q.push(nxt);
				}
			}
		} 
	}
	return -1;
}
int main()
{
	while(cin>>n>>m)
{

	for(int i=0;i<n;i++)
	{
		cin>>maps[i];
		for(int j=0;j<m;j++)
		{
			if(maps[i][j]=='S')
			{
				s.x=i;
				s.y=j;
				s.step=0;
				maps[i][j]='.';
				
			}
			if(maps[i][j]=='T')
			{
				t.x=i;
				t.y=j;
				maps[i][j]='.';
			}
		}
	}
	int res=bfs();
	cout<<res<<endl;
}
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值