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 Java from the credited upstream file 1765.java.
- 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 int[][] highestPeak(int[][] isWater) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int m = isWater.length;5 final int n = isWater[0].length;6 int[][] ans = new int[m][n];7 Arrays.stream(ans).forEach(A -> Arrays.fill(A, -1));8 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>();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.offer(new Pair<>(i, j));14 ans[i][j] = 0;15 }16 17 while (!q.isEmpty()) {18 final int i = q.peek().getKey();19 final int j = q.poll().getValue();20 for (int[] dir : DIRS) {21 final int x = i + dir[0];22 final int y = j + dir[1];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.offer(new Pair<>(x, y));29 }30 }31 32 return ans;33 }34}35