Approach
Breadth-first search
For Map of Highest Peak, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 35 lines of C++ from the credited upstream file 1765.cpp.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public:3 vector<vector<int>> highestPeak(vector<vector<int>>& isWater) {4 constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};5 const int m = isWater.size();6 const int n = isWater[0].size();7 vector<vector<int>> ans(m, vector<int>(n, -1));8 queue<pair<int, int>> q;9 10 for (int i = 0; i < m; ++i)11 for (int j = 0; j < n; ++j)12 if (isWater[i][j] == 1) {13 q.emplace(i, j);14 ans[i][j] = 0;15 }16 17 while (!q.empty()) {18 const auto [i, j] = q.front();19 q.pop();20 for (const auto& [dx, dy] : kDirs) {21 const int x = i + dx;22 const int y = j + dy;23 if (x < 0 || x == m || y < 0 || y == n)24 continue;25 if (ans[x][y] != -1)26 continue;27 ans[x][y] = ans[i][j] + 1;28 q.emplace(x, y);29 }30 }31 32 return ans;33 }34};35