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
- 68 lines of C++ from the credited upstream file 675.cpp.
- 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.
1struct T {2 int i;3 int j;4 int height;5};6 7class Solution {8 public:9 int cutOffTree(vector<vector<int>>& forest) {10 auto compare = [&](const T& a, const T& b) { return a.height > b.height; };11 priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);12 13 for (int i = 0; i < forest.size(); ++i)14 for (int j = 0; j < forest[0].size(); ++j)15 if (forest[i][j] > 1)16 minHeap.emplace(i, j, forest[i][j]);17 18 int ans = 0;19 int x = 0;20 int y = 0;21 22 while (!minHeap.empty()) {23 const auto [i, j, _] = minHeap.top();24 minHeap.pop();25 26 const int step = bfs(forest, x, y, i, j);27 if (step < 0)28 return -1;29 ans += step;30 x = i;31 y = j;32 }33 34 return ans;35 }36 37 private:38 static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};39 40 int bfs(const vector<vector<int>>& forest, int si, int sj, int ei, int ej) {41 const int m = forest.size();42 const int n = forest[0].size();43 queue<pair<int, int>> q{{{si, sj}}};44 vector<vector<bool>> seen(m, vector<bool>(n));45 seen[si][sj] = true;46 47 for (int step = 0; !q.empty(); ++step)48 for (int sz = q.size(); sz > 0; --sz) {49 const auto [i, j] = q.front();50 q.pop();51 if (i == ei && j == ej)52 return step;53 for (const auto& [dx, dy] : kDirs) {54 const int x = i + dx;55 const int y = j + dy;56 if (x < 0 || x == m || y < 0 || y == n)57 continue;58 if (seen[x][y] || forest[x][y] == 0)59 continue;60 q.emplace(x, y);61 seen[x][y] = true;62 }63 }64 65 return -1;66 };67};68