hdoj 1728(bfs+hash)(修复原版的bug)(重要)(调试的问题多就重新书写)

本文介绍了一种基于广度优先搜索(BFS)的迷宫寻路算法,该算法使用C++实现,通过定义节点类来记录迷宫中每个位置的状态,并采用队列进行节点的存储与遍历。算法考虑了转弯成本,适用于寻找从起点到终点的最短路径。
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;

#define MAX 105

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

class Node
{
public:
	int row,col,dir,cost;
};

int Row,Col;int startrow;int startcol;int endrow;int endcol;
const int lcost=1;const int rcost=1;
int k;//最大转弯次数
int result;//结果,

int mark[MAX][MAX][4];
char map[MAX][MAX];

queue<Node> q;

void check(Node next)
{
	//如果出界的话
	if(next.row<0||next.col<0||next.row>=Row||next.col>=Col)
		return ;

	//如果无法通过
	if(map[next.row][next.col]=='*')
		return;

	//如果说得到一个
	if(mark[next.row][next.col][next.dir]==-1||mark[next.row][next.col][next.dir]>next.cost)
	{
		mark[next.row][next.col][next.dir]=next.cost;
		q.push(next);

	}
}

int bfs()
{
	Node now,next;

	while(!q.empty())
	{
		now=q.front();q.pop();

		//向前走一步
		next.dir=now.dir;//方向不变
		next.cost=now.cost;//费用不变
		next.row=now.row+dir[next.dir][0];//位置改变
		next.col=now.col+dir[next.dir][1];//位置改变
		check(next);//检查

		//向右转
		next.dir=(now.dir+3)%4;//方向改变
		next.cost=now.cost+rcost;//费用改变
		next.row=now.row;//位置不变
		next.col=now.col;//位置不变
		check(next);//检查

		//向左转
		next.dir=(now.dir+1)%4;//方向改变
		next.cost=now.cost+lcost;//费用改变
		next.row=now.row;//位置不变
		next.col=now.col;//位置不变
		check(next);//检查
	}
	return 0;
}

int main()
{
	//freopen("in.txt","r",stdin);
	Node now;int i,j,k;
	int casen;scanf("%d",&casen);


	while(casen--)
	{
		//初始化

		//清空队列
		while(!q.empty())
			q.pop();

		//初始化hash
		for(i=0;i<MAX;i++)
		{
			for(j=0;j<MAX;j++)
			{
				for(k=0;k<4;k++)
				{
					mark[i][j][k]=-1;
				}
			}
		}

		//初始化reuslt
		result=100000;

		//输入
		scanf("%d %d",&Row,&Col);

		for(i=0;i<Row;i++)
			scanf("%s",map[i]);

		scanf("%d",&k);
		scanf("%d %d",&startcol,&startrow);//先输入的是列,让后才是行
		scanf("%d %d",	&endcol,  &endrow);//先输入的是列,让后才是行

		startcol--;startrow--;endcol--;endrow--;

		now.row=startrow;now.col=startcol;now.cost=0;

		//首先压入四个方向
		for(i=0;i<4;i++)
		{
			now.dir=i;mark[now.row][now.col][i]=0;
			q.push(now);
		}

		//处理
		bfs();


		//判断结果和输出
		for(i=0;i<4;i++)
		{
			if(mark[endrow][endcol][i]==-1)
			{
				continue;
			}
			if(mark[endrow][endcol][i]<result)
			{
				result=mark[endrow][endcol][i];
			}
		}
		if(result<=k)
		{
			cout<<"yes"<<endl;
		}
		else
		{
			cout<<"no"<<endl;
		}
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值