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
- 76 lines of Python from the credited upstream file 3383.py.
- The implementation visibly relies on sequence storage, ordered lookup.
- No explicit 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 def minRunesToAdd(3 self,4 n: int,5 crystals: list[int],6 flowFrom: list[int],7 flowTo: list[int]8 ) -> int:9 graph = [[] for _ in range(n)]10 reversedGraph = [[] for _ in range(n)]11 12 for u, v in zip(flowFrom, flowTo):13 graph[u].append(v)14 reversedGraph[v].append(u)15 16 17 seen = set()18 orderStack = []19 componentIds = [-1] * n20 componentCount = 021 22 for i in range(n):23 if i not in seen:24 self._kosaraju(graph, i, seen, orderStack)25 26 while orderStack:27 u = orderStack.pop()28 if componentIds[u] == -1:29 self._identifySCC(reversedGraph, u, componentIds, componentCount)30 componentCount += 131 32 33 hasCrystal = [False] * componentCount34 hasInterComponentEdge = [False] * componentCount35 36 for u in crystals:37 hasCrystal[componentIds[u]] = True38 39 for u, v in zip(flowFrom, flowTo):40 id1 = componentIds[u]41 id2 = componentIds[v]42 if id1 != id2: 43 hasInterComponentEdge[id2] = True44 45 return sum(not hasCrystal[i] and not hasInterComponentEdge[i]46 for i in range(componentCount))47 48 def _kosaraju(49 self,50 graph: list[list[int]],51 u: int,52 seen: set[int],53 orderStack: list54 ) -> None:55 """Creates a topological order stack using Kosaraju's Algorithm."""56 seen.add(u)57 for v in graph[u]:58 if v not in seen:59 self._kosaraju(graph, v, seen, orderStack)60 orderStack.append(u)61 62 def _identifySCC(63 self,64 reversedGraph: list[list[int]],65 u: int,66 componentIds: list[int],67 componentId: int68 ) -> None:69 """Assigns component IDs during SCC identification in the second DFS."""70 if componentIds[u] != -1:71 return72 componentIds[u] = componentId73 for v in reversedGraph[u]:74 if componentIds[v] == -1:75 self._identifySCC(reversedGraph, v, componentIds, componentId)76