从水源开始多源BFS
using PII = pair<int, int>;
int dx[] = {0, 1, 0, -1};
int dy[] = {1, 0, -1, 0};
class Solution {
public:
vector<vector<int>> highestPeak(vector<vector<int>>& isWater) {
queue<PII> q;
int n = isWater.size();
int m = isWater[0].size();
vector<vector<int>> ans(n, vector<int>(m, -1));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (isWater[i][j]) {
q.push({i, j});
ans[i][j] = 0;
}
}
}
int height = 1;
while (!q.empty()) {
int t = q.size();
for (int i = 0; i < t; i++) {
auto [x, y] = q.front(); q.pop();
for (int k = 0; k < 4; k++) {
int a = x + dx[k];
int b = y + dy[k];
if (a >= 0 && a < n && b >= 0 && b < m && ans[a][b] == -1) {
q.push({a, b});
ans[a][b] = height;
}
}
}
height++;
}
return ans;
}
};