杭电OJ 1026(C++)

本题使用基于优先队列的广度优先搜索,注意输出格式。

#include 
#include 
#include 
using namespace std;

const int N = 101;
char map[N][N]; //地图数组
int dis[4][2] = { { 1, 0 }, { -1, 0 }, { 0, 1 }, { 0, -1 } }; //方向数组
int n, m; //地图边长
struct grid //地图中每个格子
{
	int x, y;
	int time;
	friend bool operator<(grid a, grid b) //建立优先队列时使用,time越大,优先级越低
	{
		return a.time>b.time;
	}
};
grid path[N][N]; //路径数组

bool BFS(int &time); //广度优先搜索地图,查找最优路径
void showPath(int time, int x, int y); //输出最优路径

int main()
{
	int time;
	while (cin >> n >> m)
	{
		time = 0;
		memset(path, 0, sizeof(path)); //初始化路径数组
		for (int i = 0; i < n; i++)
		{
			for (int j = 0; j < m; j++)
			{
				cin >> map[i][j]; //读入地图信息
			}
		}
		if (BFS(time))
		{
			cout << "It takes " << time << " seconds to reach the target position, let me show you the way." << endl;
			showPath(time, n - 1, m - 1);
		}
		else
		{
			cout << "God please help our poor hero." << endl;
		}
		cout << "FINISH" << endl;
	}
	return 0;
}

bool BFS(int &time) //广度优先搜索地图,查找最优路径
{
	priority_queue q; //采用优先队列,根据所需时间选择路线
	grid start, temp; //start为目前到达的格子,temp存储上一个走过的格子
	start.x = 0;
	start.y = 0;
	start.time = 0; //开始时将start设定为起始点(0,0),此时花费的时间为0
	q.push(start); //将起始点(根结点)入队列,执行广度优先搜索
	while (!q.empty())
	{
		start = q.top(); //此时队列头的格子为start
		q.pop();
		if (start.x == n - 1 && start.y == m - 1)
		{
			time = start.time;
			return true;
		}
		temp = start; //存储当前格子
		for (int i = 0; i < 4; i++) //搜索当前格子的上下左右四个方向
		{
			start.x = temp.x + dis[i][0];
			start.y = temp.y + dis[i][1];
			start.time = temp.time + 1;
			if (start.x < 0 || start.y < 0 || start.x >= n || start.y >= m || map[start.x][start.y] == 'X')
				continue;
			path[start.x][start.y] = temp; //将刚刚走过的格子存储到路径数组中
			path[start.x][start.y].time = 0; //将格子所需时间初始化为0
			if (map[start.x][start.y] != '.') //当前节点为数字,即所需时间不为0
			{
				start.time += map[start.x][start.y] - '0'; //在已走路径总用时上加上当前格子用时
				path[start.x][start.y].time = map[start.x][start.y] - '0'; //为路径数组中当前格子所需时间赋值
			}
			map[start.x][start.y] = 'X'; //已走过的格子封闭,不再重复走
			q.push(start); //将当前格子入队列(按照优先队列原则,time值小的优先级高)
		}
	}
	return false;
}

void showPath(int time, int x, int y) //输出最优路径
{
	if (time == 0)
		return;
	time -= path[x][y].time;
	showPath(time - 1, path[x][y].x, path[x][y].y); //从终点向起点递归遍历路径数组
	cout << time++ << "s:(" << path[x][y].x << "," << path[x][y].y << ")->(" << x << "," << y << ")" << endl;
	while (path[x][y].time--)
		cout << time++ << "s:FIGHT AT (" << x << "," << y << ")" << endl;
}

 

你可能感兴趣的:(杭电OJ)