LeetCode 1765 地图中的最高点

题目链接:LeetCode 1765 地图中的最高点

题目大意:

题解:
题目要求水域的高度必须为\(0\),因此水域的高度是已经确定的值,我们可以从水域出发,推导出其余格子的高度。

  • 首先,计算与水域相邻的格子的高度。对于这些格子来说,其相邻格子中的最小高度即为水域的高度\(0\),因此这些格子的高度为\(1\)
  • 然后,计算与高度为\(1\)的格子相邻的、尚未被计算过的格子的高度。对于这些格子来说,其相邻格子中的最小高度为\(1\),因此这些格子的高度为\(2\)
  • 以此类推,计算出所有格子的高度。

可以用多源广度优先搜索来实现。

class Solution {
private:
    int dirs[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};

public:
    vector<vector<int>> highestPeak(vector<vector<int>>& isWater) {
        int m = isWater.size(), n = isWater[0].size();
        vector<vector<int>> ans(m, vector<int>(n, -1));
        queue<pair<int, int>> que;
        for (int i = 0; i < m; ++i) {
            for (int j = 0; j < n; ++j) {
                if (isWater[i][j]) {
                    ans[i][j] = 0;
                    que.emplace(i, j);
                }
            }
        }
        while (!que.empty()) {
            auto& p = que.front();
            for (auto& dir : dirs) {
                int x = p.first + dir[0], y = p.second + dir[1];
                if (x >= 0 && x < m && y >= 0 && y < n && !(~ans[x][y])) {
                    ans[x][y] = ans[p.first][p.second] + 1;
                    que.emplace(x, y);
                }
            }
            que.pop();
        }
        return ans;
    }
};
posted @ 2022-02-07 13:26  ZZHHOOUU  阅读(27)  评论(0编辑  收藏  举报