POJ1376

#include<iostream>
#include<queue>
#include<cstdio>
#define inf 10e6
using namespace std;
struct node
{
	int x,y,f,step;
};
int dir[4][2]={0,1,1,0,0,-1,-1,0};
int n,m,ex,ey;
int g[55][55],dis[55][55][4];
char face[20];
node start;
bool can(int x,int y,node cur)    
{
    return x>0 && x<n && y>0 && y<m && (cur.step+1<dis[x][y][cur.f]);
}
int bfs()
{
	queue<node> q;
	while(!q.empty()) q.pop();
	q.push(start);
	
	while(!q.empty())
	{
		node cur = q.front();
		if(cur.x==ex && cur.y==ey) 
		  return cur.step;
		if(cur.step+1<dis[cur.x][cur.y][(cur.f+1)%4])
		{
			node np;
			np=cur;
			np.step++;
			np.f=(cur.f+1)%4;
			q.push(np);
			
			dis[cur.x][cur.y][(cur.f+1)%4] = cur.step;
		}
		if(cur.step+1<dis[cur.x][cur.y][(cur.f+3)%4])
		{
			node np;
			np=cur;
			np.step++;
			np.f=(cur.f+3)%4;
			q.push(np);
			
			dis[cur.x][cur.y][(cur.f+3)%4] = cur.step;
		}
		for(int i=1;i<=3;i++)
		{
			int nx = cur.x + i*dir[cur.f][0];
			int ny = cur.y + i*dir[cur.f][1];
			if(g[nx][ny]==1) break;
			if(can(nx,ny,cur))
			{
				node np;
				np=cur;
				np.x=nx;
				np.y=ny;			
				np.step++;
				q.push(np);
				
				dis[np.x][np.y][np.f] = np.step;
			}
		}
		q.pop(); 
	}
	return -1;
}
int main()
{
	int t;
	
	while(scanf("%d%d",&n,&m)!=EOF && n!=0 && m!=0) 
	{
		memset(g,0,sizeof(g));
		
		for(int i=0;i<n;i++)
		 for(int j=0;j<m;j++)
		 {
		 	int temp;
	        cin>>temp;                    
	        if (temp==1)
	        {
	           g[i][j]=g[i][j+1]=g[i+1][j]=g[i+1][j+1]=1;      
	        }   
	        dis[i][j][0]=dis[i][j][1]=dis[i][j][2]=dis[i][j][3]=inf; 
		}
		scanf("%d%d%d%d%s",&start.x,&start.y,&ex,&ey,face);
		  
		if(face[0]=='e') t=0;
		else if(face[0]=='s') t=1;
		else if(face[0]=='w') t=2;
		else if(face[0]=='n') t=3;
		start.f=t;		
		start.step=0;
		
		cout<<bfs()<<endl;
	}
	return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值