题目
翻译

迷宫的状态会改变,最开始没想明白怎么用bfs去做,不过提供翻译的那个博主给了思路,把问题分解成多次简单的bfs。

#include <iostream>
#include <cstring>
#include <queue>
#include <fstream>
#include <algorithm>
using namespace std;

const int MAX_SIZE = 1000;
struct Coordinate{
	int row;
	int col;
};
Coordinate start, goal;//记录起点,终点坐标
Coordinate mov_dir[4] = {{1, 0}, {0, -1}, {-1, 0}, {0, 1}};//四个方向,顺时针
queue<Coordinate>que;
int H, W, N;
char maze[MAX_SIZE + 1][MAX_SIZE + 1];
int cnt_time[MAX_SIZE + 1][MAX_SIZE + 1];//记录到达每个点需要的时间

int bfs()
{
	while (que.size()){
		Coordinate head = que.front();
		if (head.row == goal.row && head.col == goal.col)
			return cnt_time[head.row][head.col];
		que.pop();
		Coordinate tmp;
		for (int i = 0; i < 4; i++) {

			tmp.row = head.row + mov_dir[i].row;
			tmp.col = head.col + mov_dir[i].col;

			if (tmp.row >=0 && tmp.row < H && tmp.col >= 0 && tmp.col < W &&
			maze[tmp.row][tmp.col] != 'X' && cnt_time[tmp.row][tmp.col] == -1){
				que.push(tmp);
				cnt_time[tmp.row][tmp.col] = cnt_time[head.row][head.col] + 1;
			}
		}
	}
}
void ClearQueue(queue<Coordinate> &tmp)
{
	queue<Coordinate> empty;
	swap(empty, tmp);
}
int main()
{
	// ifstream IN("IN.txt", ios::in);
	cin >> H >> W >> N;
	char cheese[10];//记录N个奶酪的硬度(包含起点)
	Coordinate cheese_pos[10];//记录N个奶酪的坐标(包含起点)
	int cnt = 0;//记录奶酪的个数(包含起点)
	for (int i = 0; i < H; i++) {
		for (int j = 0; j < W; j++) { 
			cin >> maze[i][j];
			if (maze[i][j] != '.' && maze[i][j] != 'X'){
				if (maze[i][j] == 'S') {
					maze[i][j] = '0';//把S 改为'0';
				}

				cheese[cnt++] = maze[i][j];
				cheese_pos[maze[i][j] - '0'].row = i;
				cheese_pos[maze[i][j] - '0'].col = j;
			}
		}
	}

	sort(cheese, cheese + cnt);//排序,因为吃奶酪一定是按硬度从低到高的顺序。
	int ans = 0;
	for (int i = 0; i < cnt - 1; i++) {//每次吃到的奶酪的坐标就是下一次搜索的起点

		start.row = cheese_pos[i].row;
		start.col = cheese_pos[i].col;
		goal.row = cheese_pos[i + 1].row;
		goal.col = cheese_pos[i + 1].col;

		que.push(start);
		memset(cnt_time, -1, sizeof(cnt_time));
		cnt_time[start.row][start.col] = 0;
		ans += bfs();
		ClearQueue(que);
	}
	cout << ans << endl;
	return 0;
}
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐