本文共 2995 字,大约阅读时间需要 9 分钟。
这道题的目标是通过计算Y和M到同一个KFC的最短路径之和,找出最小的总时间。以下是详细的解题步骤和代码实现。
#include#include #include #include using namespace std;#define INF 99999999#define MAX 233struct node { int x, y;};queue Q;int x1, y1, x2, y2;char grid[MAX][MAX];int book[MAX][MAX][2];int nxt[4][2] = {{1, 0}, {0, -1}, {-1, 0}, {0, 1}};int can_move(int x, int y, int tag) { if (x < 0 || x >= n || y < 0 || y >= m) return 0; if (book[x][y][tag] != 0) return 0; if (grid[x][y] == 'y' || grid[x][y] == 'm' || grid[x][y] == '#') return 0; return 1;}void bfs(node start, int tag) { book[start.x][start.y][tag] = 0; Q.push(start); while (!Q.empty()) { node current = Q.front(); Q.pop(); for (int i = 0; i < 4; ++i) { int tx = current.x + nxt[i][0]; int ty = current.y + nxt[i][1]; if (can_move(tx, ty, tag)) { if (book[tx][ty][tag] == INF) { book[tx][ty][tag] = book[current.x][current.y][tag] + 1; node new_node; new_node.x = tx; new_node.y = ty; Q.push(new_node); } } } }}int main() { while (scanf("%d%d", &n, &m) != EOF) { for (int i = 0; i < n; ++i) { scanf("%s", grid[i]); for (int j = 0; j < m; ++j) { if (grid[i][j] == 'Y') { x1 = i, y1 = j; } else if (grid[i][j] == 'M') { x2 = i, y2 = j; } else if (grid[i][j] == '@') { int k = i; int l = j; // Skip processing KFC for now } } } node start_y; start_y.x = x1, start_y.y = y1; bfs(start_y, 0); node start_m; start_m.x = x2, start_m.y = y2; bfs(start_m, 1); int min_total = INF; for (int i = 0; i < n; ++i) { for (int j = 0; j < m; ++j) { if (grid[i][j] == '@') { if (book[i][j][0] != 0 && book[i][j][1] != 0) { int total = book[i][j][0] + book[i][j][1]; if (total < min_total) { min_total = total; } } } } } printf("%d\n", min_total * 11); memset(book, 0, sizeof(book)); } return 0;}
node结构体用于存储坐标。book数组。通过以上步骤,我们可以高效地解决问题,找到Y和M到同一个KFC的最短路径之和,并输出结果。该方法利用BFS算法,确保了计算的准确性和效率。
转载地址:http://lqxfk.baihongyu.com/