Approach
Depth-first search
For Minimum Runes to Add to Cast Spell, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 80 lines of Java from the credited upstream file 3383.java.
- The implementation visibly relies on sequence storage.
- 9 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
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 minRunesToAdd(int n, int[] crystals, int[] flowFrom, int[] flowTo) {3 List<Integer>[] graph = new ArrayList[n];4 List<Integer>[] reversedGraph = new ArrayList[n];5 6 for (int i = 0; i < n; ++i) {7 graph[i] = new ArrayList<>();8 reversedGraph[i] = new ArrayList<>();9 }10 11 for (int i = 0; i < flowFrom.length; ++i) {12 final int u = flowFrom[i];13 final int v = flowTo[i];14 graph[u].add(v);15 reversedGraph[v].add(u);16 }17 18 19 boolean[] seen = new boolean[n];20 List<Integer> orderStack = new ArrayList<>();21 int[] componentIds = new int[n];22 int componentCount = 0;23 24 for (int i = 0; i < n; ++i)25 if (!seen[i])26 kosaraju(graph, i, seen, orderStack);27 28 Arrays.fill(componentIds, -1);29 30 for (int i = orderStack.size() - 1; i >= 0; --i) {31 final int u = orderStack.get(i);32 if (componentIds[u] == -1)33 identifySCC(reversedGraph, u, componentIds, componentCount++);34 }35 36 37 boolean[] hasCrystal = new boolean[componentCount];38 boolean[] hasInterComponentEdge = new boolean[componentCount];39 40 for (final int u : crystals)41 hasCrystal[componentIds[u]] = true;42 43 for (int i = 0; i < flowFrom.length; ++i) {44 final int id1 = componentIds[flowFrom[i]];45 final int id2 = componentIds[flowTo[i]];46 if (id1 != id2)47 hasInterComponentEdge[id2] = true;48 }49 50 51 int ans = 0;52 53 for (int i = 0; i < componentCount; ++i)54 if (!hasCrystal[i] && !hasInterComponentEdge[i])55 ++ans;56 57 return ans;58 }59 60 61 private void kosaraju(List<Integer>[] graph, int u, boolean[] seen, List<Integer> orderStack) {62 seen[u] = true;63 for (final int v : graph[u])64 if (!seen[v])65 kosaraju(graph, v, seen, orderStack);66 orderStack.add(u);67 }68 69 70 private void identifySCC(List<Integer>[] reversedGraph, int u, int[] componentIds,71 int componentId) {72 if (componentIds[u] != -1)73 return;74 componentIds[u] = componentId;75 for (final int v : reversedGraph[u])76 if (componentIds[v] == -1)77 identifySCC(reversedGraph, v, componentIds, componentId);78 }79}80