Approach
Breadth-first search
For Minimum Jumps to Reach End Via Prime Teleportation, 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
- 74 lines of C++ from the credited upstream file minimum-jumps-to-reach-end-via-prime-teleportation.cpp.
- The implementation visibly relies on sequence storage, hash lookup.
- 9 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.
1234 56vector<int> linear_sieve_of_eratosthenes(int n) { 7 vector<int> spf(n + 1, -1);8 vector<int> primes;9 for (int i = 2; i <= n; ++i) {10 if (spf[i] == -1) {11 spf[i] = i;12 primes.emplace_back(i);13 }14 for (const auto& p : primes) {15 if (i * p > n || p > spf[i]) {16 break;17 }18 spf[i * p] = p;19 }20 }21 return spf;22};23 24const int MAX_NUM = 1e6;25const auto& SPF = linear_sieve_of_eratosthenes(MAX_NUM);26class Solution {27public:28 int minJumps(vector<int>& nums) {29 unordered_map<int, vector<int>> adj;30 for (int i = 0; i < size(nums); ++i) {31 int x = nums[i];32 while (x != 1) {33 const auto& p = SPF[x];34 while (x % p == 0) {35 x /= p;36 }37 adj[p].emplace_back(i);38 }39 }40 vector<int> dist(size(nums), -1);41 dist[0] = 0;42 vector<int> q = {0};43 while (!empty(q)) {44 vector<int> new_q;45 for (const auto& i : q) {46 if (i == size(nums) - 1) {47 return dist.back();48 }49 for (const auto& di : {-1, +1}) {50 const int ni = i + di;51 if (0 <= ni && ni < size(nums) && dist[ni] == -1) {52 dist[ni] = dist[i] + 1;53 new_q.emplace_back(ni);54 }55 }56 const int p = nums[i];57 if (SPF[p] != p || !adj.count(p)) {58 continue;59 }60 for (const auto& ni : adj[p]) {61 if (dist[ni] != -1) {62 continue;63 }64 dist[ni] = dist[i] + 1;65 new_q.emplace_back(ni);66 }67 adj.erase(p);68 }69 q = move(new_q);70 }71 return -1;72 }73};74