uva 10047

这题明显和普通的bfs不一样,因为普通的bfs就是vis[][]二维状态的搜索,走过以后的路径是不能退回的,但是这里应该是可以退回,所以用了个vis[x][y][dir][color]

dir 在x,y格子上 表示当前的方向,color表示在x y 格子上当前的颜色。 

还有就是这个轮子方向要旋转,所以有时候后一格并不能一个时间单位走到,要先在原地旋转,然后把时间累加到原地的格子上,然后再往前走,这个类似坦克破墙搜索,加个优先队列就可以解决了。为了方便起见优先队列我用c++的STL。如果纯C的话,可以用二叉堆维护优先队列。


最后一个bug 我怎么也搞不清楚,就是STL的优先队列priority_queue<node> q; 必须放在bfs()函数里, 只要放到全局变量就wa,求大神解释

下面是ac代码

#include<iostream>
#include<queue>
#include<cmath> 
#include <cstdio>
#include <string>
#include <cstdlib>
#include <string.h>
#define MAX 30
using namespace std;
char map[MAX][MAX];
int vis[MAX][MAX][4][5];
int m, n;
int d[4][2] = {{-1,0},{0,-1},{1,0},{0,1}};
struct node  
{  
    int x,y;  
    int time, color, dir; 
    friend bool operator < ( node a, node b )  
    { 
        return a.time > b.time;   
    }  
}; 

int bfs( int x, int y )
{
	node temp, start;
	priority_queue<node> q;
	start.x = x;
	start.y = y;
	start.time = 0;
	start.color = 0;		
	start.dir = 0;		 
	q.push( start );
	vis[start.x][start.y][0][0] = 1;
	while( !q.empty() )
	{
		start = q.top();
		q.pop();
		for( int i = 0; i < 4; i++ )
		{
				if( start.dir != i )                                 
				{
					temp.x = start.x;
					temp.y = start.y;
					int a = (int)fabs(start.dir-i);
					if( a == 2 )
						temp.time = start.time + 2;
					else
						temp.time = start.time + 1;
					temp.dir = i;
					temp.color = start.color;
				}
				else
				{
					temp.x = start.x + d[i][0];
					temp.y = start.y + d[i][1];
					temp.time = start.time+1;
					temp.color = (start.color+1)%5;
					temp.dir = start.dir;
				}
				if(  !(temp.x >= 0 && temp.x < m && temp.y >= 0 && temp.y < n && map[temp.x][temp.y] != '#')  )
					continue;
				if( !vis[temp.x][temp.y][temp.dir][temp.color] )
				{
					if( map[temp.x][temp.y] == 'T' && temp.color == 0 )
						return temp.time;
					vis[temp.x][temp.y][temp.dir][temp.color] = 1;
					q.push(temp);
				}
		}
	}
	return -1;
};
int main()
{
	int val, time = 1, c, sx, sy;
	while( scanf( "%d%d\n", &m, &n ) && m && n )
	{
		for( int i = 0; i < m; i++ )
		{
			for( int j = 0; j < n; j++ )
			{
				if( (c = getchar()) == 'S' )
				{
					sx = i;
					sy = j;
				}
				map[i][j] = c;
			}
			scanf( "\n" );
		}
		memset( vis, 0, sizeof(vis) );
		val = bfs( sx, sy );
		if( time != 1 )
			printf( "\n" );
		printf( "Case #%d\n", time++ );
		if( val == -1 )
			printf( "destination not reachable\n");	
		else
			printf( "minimum time = %d sec\n", val );
	}
	return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值