URAL 1254 Die Hard (SPFA)

#include <stdio.h>
#define MAX_SIZE 75
#define MAX_BOMBS 1000
#define SQUARE_ROOT_2 1.414213562373095048
#define MAX_DISTANCE 5626

int xSize, ySize, numOfBombs;
double velocity;
char map[MAX_SIZE + 1][MAX_SIZE + 1];
typedef struct Location{
	int x;
	int y;
}Location;
Location queue[10000];//注意数组别开小了
int head, tail;
Location directionArray[8] = {{0, -1}, {0, 1}, {-1, 0}, {1, 0}, {1, -1}, {1, 1}, {-1, 1}, {-1, -1}};
double distanceArray[MAX_BOMBS + 1][MAX_BOMBS + 1];
double totalDistance;

void printfDistance(){
	int x, y;
	for (y = 1; y <= ySize; y++){
		for (x = 1; x <= xSize; x++)
			printf("%7.2lf ", distanceArray[y][x]);
		printf("\n");
	}
	printf("\n");		
}

int main(){

	scanf("%d%d%d%lf", &xSize, &ySize, &numOfBombs, &velocity);

	int y, x;
	for (y = 1; y <= ySize; y++)
		for (x = 1; x <= xSize; x++)
			scanf(" %c", &map[y][x]);

	Location LocationPushed;
	scanf("%d%d", &LocationPushed.x, &LocationPushed.y);

	int bomb;
	for (bomb = 1; bomb <= numOfBombs; bomb++){
		Location bombLocation;
		scanf("%d%d", &bombLocation.x, &bombLocation.y);

		for (y = 1; y <= ySize; y++)
			for (x = 1; x <= xSize; x++)	
				distanceArray[y][x] = MAX_DISTANCE;

		head = tail = 0;
		queue[tail++] = LocationPushed;
		distanceArray[LocationPushed.y][LocationPushed.x] = 0;

		//SPFA:注意不能用简单的BFS,因为有每个点有多条边,先到的路径不一定就是路程最短的路径
		while (head < tail){
			Location LocationPoped = queue[head++];
			int directionIndex;
			for (directionIndex = 0; directionIndex < 8; directionIndex++){
				x = LocationPoped.x + directionArray[directionIndex].x;
				y = LocationPoped.y + directionArray[directionIndex].y;
				if (x < 1 || x > xSize || y < 1 || y > ySize || map[y][x] == '#')
					continue;
				//注意是路程最短的点,不是常规的最短路径
				double distance = distanceArray[LocationPoped.y][LocationPoped.x] + (directionIndex < 4 ? 1.0 :  1.414213562373095048);
				if (distance < distanceArray[y][x]){
					distanceArray[y][x] = distance;
					LocationPushed.x = x;
					LocationPushed.y = y;
					queue[tail++] = LocationPushed;
				}
			}
		}

		if (distanceArray[bombLocation.y][bombLocation.x] < MAX_DISTANCE){
			totalDistance += distanceArray[bombLocation.y][bombLocation.x];
			LocationPushed = bombLocation;
		} else 
			LocationPushed = queue[0];
	}

	printf("%.2lf\n", totalDistance / velocity);

	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值