文章

454

粉丝

0

获赞

1

访问

9.5k

头像
高尔夫比赛的森林砍树 题解(C++ AC 代码)
P5377 复旦大学2023年机试题
发布于 2026年11月
阅读数 14

题意

m×n 网格,0 是障碍,按树高从低到高依次砍树,求从 (0,0) 出发的最小总步数,砍不完输出 -1。

思路

  • 把树按高度排序,起点设为 (0,0)。

  • 每次从当前位置 BFS 到下一棵树,累加最短距离,更新当前位置。

  • 若某次 BFS 不可达,直接输出 -1。

复杂度

O(mn * 树的个数)。

参考代码(C++)

C++:

#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
using namespace std;

int g[55][55], dist[55][55];
int m, n;
const int dx[4] = {-1, 1, 0, 0}, dy[4] = {0, 0, -1, 1};

int bfs(int sx, int sy, int tx, int ty) {
    for (int i = 0; i < m; i++)
        for (int j = 0; j < n; j++) dist[i][j] = -1;
    if (g[sx][sy] == 0) return -1;
    dist[sx][sy] = 0;
    queue<int> q;
    q.push(sx * n + sy);
    while (!q.empty()) {
        int id = q.front(); q.pop();
        int x = id / n, y = id % n;
        if (x == tx && y == ty) return dist[x][y];
        for (int k = 0; k < 4; k++) {
            int nx = x + dx[k], ny = y + dy[k];
            if (nx < 0 || nx >= m || ny < 0 || ny >= n) continue;
            if (g[nx][ny] == 0 || dist[nx][ny] != -1) co...
登录查看完整内容


登录后发布评论

暂无评论,来抢沙发