Approach
Breadth-first search
For Minimum Jumps to Reach Home, 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
- 38 lines of C++ from the credited upstream file 1654.cpp.
- The implementation visibly relies on sequence storage, hash lookup, work queue.
- 3 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.
1enum class Direction { kForward, kBackward };2 3class Solution {4 public:5 int minimumJumps(vector<int>& forbidden, int a, int b, int x) {6 int furthest = x + a + b;7 unordered_set<int> seenForward;8 unordered_set<int> seenBackward;9 10 for (const int pos : forbidden) {11 seenForward.insert(pos);12 seenBackward.insert(pos);13 furthest = max(furthest, pos + a + b);14 }15 16 17 queue<pair<Direction, int>> q{{{Direction::kForward, 0}}};18 19 for (int ans = 0; !q.empty(); ++ans)20 for (int sz = q.size(); sz > 0; --sz) {21 const auto [dir, pos] = q.front();22 q.pop();23 if (pos == x)24 return ans;25 const int forward = pos + a;26 const int backward = pos - b;27 if (forward <= furthest && seenForward.insert(forward).second)28 q.emplace(Direction::kForward, forward);29 30 if (dir == Direction::kForward && backward >= 0 &&31 seenBackward.insert(backward).second)32 q.emplace(Direction::kBackward, backward);33 }34 35 return -1;36 }37};38