Approach
Breadth-first search
For As Far from Land as Possible, 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
- 42 lines of Java from the credited upstream file 1162.java.
- The implementation visibly relies on sequence storage, work queue.
- 5 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 maxDistance(int[][] grid) {3 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};4 final int m = grid.length;5 final int n = grid[0].length;6 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>();7 int water = 0;8 9 for (int i = 0; i < m; ++i)10 for (int j = 0; j < n; ++j)11 if (grid[i][j] == 0)12 ++water;13 else14 q.offer(new Pair<>(i, j));15 16 if (water == 0 || water == m * n)17 return -1;18 19 int ans = 0;20 21 for (int d = 0; !q.isEmpty(); ++d)22 for (int sz = q.size(); sz > 0; --sz) {23 Pair<Integer, Integer> pair = q.poll();24 final int i = pair.getKey();25 final int j = pair.getValue();26 ans = d;27 for (int[] dir : DIRS) {28 final int x = i + dir[0];29 final int y = j + dir[1];30 if (x < 0 || x == m || y < 0 || y == n)31 continue;32 if (grid[x][y] > 0)33 continue;34 q.offer(new Pair<>(x, y));35 grid[x][y] = 2; 36 }37 }38 39 return ans;40 }41}42