【BFS终于变水】HDU 1242——Rescue

来源:点击打开链接

终于把BFS看水了,包括路径优化和奇偶剪枝。一年了也就看明白了这点东西,so sad。。。。

#include <iostream>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;

int visited[205][205];
char mat[205][205];
int n,m;
int dir[4][2]={-1,0,1,0,0,1,0,-1};

class node
{
	public:
		int x;
		int y;
		int step;
};

bool judge(int x,int y)
{
	if(x>=0 && x<n && y>=0 && y<m && visited[x][y]==0 && mat[x][y]!='#')
		return 1;
	else
		return 0;
}

int bfs(node st,node ed)
{
	memset(visited,0,sizeof(visited));
	queue<node> q;
	node first,next;
	first.x=st.x;
	first.y=st.y;
	first.step=0;
	visited[first.x][first.y]=1;
	q.push(first);
	while(!q.empty())
	{
		first=q.front();
		q.pop();
		for(int i=0;i<4;i++)
		{
			next.x=first.x+dir[i][0];
			next.y=first.y+dir[i][1];
			next.step=first.step;
			if(next.x==ed.x && next.y==ed.y)
				return next.step+1;
			if(judge(next.x,next.y) && mat[next.x][next.y]=='.')
			{
				next.step+=1;
				visited[next.x][next.y]=1;
				q.push(next);
			}
			if(judge(next.x,next.y) && mat[next.x][next.y]=='x')
			{
				next.step+=2;
				visited[next.x][next.y]=1;
				q.push(next);
			}
			
		}
		
	}
	return -1;
}

int main()
{
	while(cin>>n>>m)
	{
		node s1,e1;
		for(int i=0;i<n;i++)
		{
			for(int j=0;j<m;j++)
			{
				cin>>mat[i][j];
				if(mat[i][j]=='a')
				{
					s1.x=i;
					s1.y=j;
				}
				if(mat[i][j]=='r')
				{
					e1.x=i;
					e1.y=j;
				}
			}
		}
		int res=bfs(s1,e1);
		if(res!=-1)
		{
			cout<<res<<endl;
		}
		else
		{
			cout<<"Poor ANGEL has to stay in the prison all his life."<<endl;
		}
	}
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值