Problem Description
We are given n focus points. Some focus points hold magic crystals and there exist pre‐established directed runes (edges) that channel magic from one focus point to another. To successfully cast the spell, every focus point must either contain a crystal or be able to receive magic from another focus point (via one or more directed rune flows). The task is to return the minimum number of additional directed runes that must be added so that every focus point satisfies this property.
Key Insights
- The directed rune network can be viewed as a graph where nodes (focus points) are “powered” if they initially contain a crystal.
- Magic can propagate: if a powered node has a directed edge to another node, that node becomes powered.
- Compute, by BFS/DFS, the set of nodes reachable (and therefore powered) starting from all nodes that have crystals.
- Not powered nodes possibly form separate connected “components” (through their directed connectivity) that can be powered by adding a single rune into each component.
- The answer is the number of such disjoint groups (of unpowered nodes) that cannot be reached by any propagation starting from an initial crystal.
Space and Time Complexity
Time Complexity: O(n + m), where m is the number of existing runes.
Space Complexity: O(n + m) for storing the graph and auxiliary data structures.
Solution
We first build a graph with an adjacency list to represent existing directed runes. Then, we start from every focus point that initially contains a magic crystal and perform a BFS (or DFS) to mark every focus point that becomes powered through propagation. After this, any focus point that remains unpowered must be addressed by adding a new directed rune. However, note that adding a rune to any one focus point in a connected group of unpowered nodes will power the entire group (because magic will then cascade through their outgoing connections). Thus, we perform another BFS/DFS over the unpowered nodes grouped by connectivity (using the same directed edges) and count one additional rune per group.
The key mental leap is to recognize that powering one node in each “component” of unreachable nodes is enough to make the entire component powered, hence we only add as many runes as there are unpowered connected groups.