Approach
Breadth-first search
For Unit Conversion II, 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
- 56 lines of Java from the credited upstream file 3535.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[] queryConversions(int[][] conversions, int[][] queries) {3 int[] units = baseUnitConversions(conversions);4 int[] ans = new int[queries.length];5 6 for (int i = 0; i < queries.length; ++i) {7 final int u = queries[i][0];8 final int v = queries[i][1];9 10 ans[i] = (int) ((long) units[v] * modPow(units[u], MOD - 2) % MOD);11 }12 13 return ans;14 }15 16 private static final int MOD = 1_000_000_007;17 18 private int[] baseUnitConversions(int[][] conversions) {19 final int n = conversions.length + 1;20 int[] ans = new int[n];21 ans[0] = 1;22 Queue<Integer> q = new ArrayDeque<>(Arrays.asList(0));23 List<Pair<Integer, Integer>>[] graph = new List[n];24 25 for (int i = 0; i < n; i++)26 graph[i] = new ArrayList<>();27 28 for (int[] conversion : conversions) {29 final int u = conversion[0];30 final int v = conversion[1];31 final int factor = conversion[2];32 graph[u].add(new Pair<>(v, factor));33 }34 35 while (!q.isEmpty()) {36 final int u = q.poll();37 for (Pair<Integer, Integer> pair : graph[u]) {38 final int v = pair.getKey();39 final int factor = pair.getValue();40 ans[v] = (int) ((long) ans[u] * factor % MOD);41 q.offer(v);42 }43 }44 45 return ans;46 }47 48 private int modPow(long x, long n) {49 if (n == 0)50 return 1;51 if (n % 2 == 1)52 return (int) (x * modPow(x % MOD, (n - 1)) % MOD);53 return modPow(x * x % MOD, (n / 2)) % MOD;54 }55}56