Approach
Breadth-first search
For Cut Off Trees for Golf Event, 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
- 60 lines of Java from the credited upstream file 675.java.
- The implementation visibly relies on sequence storage, work queue.
- 6 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 cutOffTree(List<List<Integer>> forest) {3 record T(int i, int j, int height) {}4 Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::height));5 6 for (int i = 0; i < forest.size(); ++i)7 for (int j = 0; j < forest.get(0).size(); ++j)8 if (forest.get(i).get(j) > 1)9 minHeap.offer(new T(i, j, forest.get(i).get(j)));10 11 int ans = 0;12 int x = 0;13 int y = 0;14 15 while (!minHeap.isEmpty()) {16 final int i = minHeap.peek().i;17 final int j = minHeap.poll().j;18 19 final int step = bfs(forest, x, y, i, j);20 if (step < 0)21 return -1;22 ans += step;23 x = i;24 y = j;25 }26 27 return ans;28 }29 30 private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};31 32 private int bfs(List<List<Integer>> forest, int si, int sj, int ei, int ej) {33 final int m = forest.size();34 final int n = forest.get(0).size();35 Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(si, sj)));36 boolean[][] seen = new boolean[m][n];37 seen[si][sj] = true;38 39 for (int step = 0; !q.isEmpty(); ++step)40 for (int sz = q.size(); sz > 0; --sz) {41 final int i = q.peek().getKey();42 final int j = q.poll().getValue();43 if (i == ei && j == ej)44 return step;45 for (int[] dir : DIRS) {46 final int x = i + dir[0];47 final int y = j + dir[1];48 if (x < 0 || x == m || y < 0 || y == n)49 continue;50 if (seen[x][y] || forest.get(x).get(y) == 0)51 continue;52 q.offer(new Pair<>(x, y));53 seen[x][y] = true;54 }55 }56 57 return -1;58 };59}60