hdoj1026 Ignatius and the Princess I(图bfs+栈)

感觉自己还有好长好长的路要走。。

考察:bfs时用到队列找到最优路线,用栈存储经过的点并输出。

#include<iostream> 
#include<queue>
#include<stack>
using namespace std;
typedef struct point
{
	int x,y,cost,prex,prey;
}point;//点结构体,包含当前点的坐标以及前一点的坐标和到这个点所需要的时间 
char map[105][105];
point p[105][105];
int dir[4][2]={-1,0,1,0,0,-1,0,1};
int n,m;
bool open(int x,int y)//判断是否能够通行 
{
	if(x<n&&x>=0&&y<m&&y>=0&&map[x][y]!='X')
	return 1;
	else
	return 0;
}
void printpath(int x,int y)//利用栈来存储路径,并输出 
{
	stack<point>s;
	int i=1,j;
	point a,b;
	cout<<"It takes "<<p[n-1][m-1].cost<<" seconds to reach the target position,let me show you the way."<<endl;
	a=p[x][y];
	while(1)
	{
		if(a.x==0&&a.y==0)break;
		s.push(a);
		a=p[a.prex][a.prey];
	}
	a=p[0][0];
	while(!s.empty())
	{
		b=s.top();
		s.pop();
		if(map[b.x][b.y]=='.')
		{
			cout<<i++<<"s:("<<a.x<<","<<a.y<<")->("<<b.x<<","<<b.y<<")"<<endl;
		}
		else
		{
			j=map[b.x][b.y]-'0';
			cout<<i++<<"s:("<<a.x<<","<<a.y<<")->("<<b.x<<","<<b.y<<")"<<endl;
			while(j--)
			cout<<i++<<"s:FIGHT AT ("<<b.x<<","<<b.y<<")"<<endl;
		}
		a=b;
		
	}
	cout<<"FINISH"<<endl;
}

int bfs(int x,int y)//利用队列进行bfs,为p[][]赋值,找到最优路线 
{
   queue<point>que;
   point a,b;
   int i,j;
   a.x=a.y=a.prex=a.prey=a.cost=0;
   p[0][0]=a;
   que.push(a);	
   while(!que.empty())
   {
   	a=que.front();
   	que.pop();
   	for(i=0;i<4;i++)
   	{
   		b.x=a.x+dir[i][0];
   		b.y=a.y+dir[i][1];
   		if(!open(b.x,b.y))continue;
   		else
   		{
   			if(map[b.x][b.y]!='.')
   			j=map[b.x][b.y]-'0';
   			else j=0;
		 b.prex=a.x;b.prey=a.y;
		 b.cost=a.cost+1+j;	
	    }  	
	    if(b.cost<p[b.x][b.y].cost||p[b.x][b.y].cost==-1)
	    {
	    	 
	    	 p[b.x][b.y]=b;
    		que.push(b);
    	}
    }
   }
   if(p[n-1][m-1].cost==-1)
   {cout<<"God please help our poor hero."<<endl;
    cout<<"FINISH"<<endl;
   return 0;}
   printpath(n-1,m-1);
}
int main()
{
	int i,j;
	while(cin>>n>>m)
	{
		memset(map,0,sizeof(map));
		for(i=0;i<n;i++)
		for(j=0;j<m;j++)
		{
		p[i][j].cost=-1;
		cin>>map[i][j];
		}
		bfs(0,0);
		
	}
	return 0;
}





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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值