Approach
Depth-first search
For Throne Inheritance, 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
- 35 lines of Java from the credited upstream file 1600.java.
- The implementation visibly relies on sequence storage, hash lookup, ordered lookup.
- 1 loop block 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 ThroneInheritance {2 public ThroneInheritance(String kingName) {3 this.kingName = kingName;4 }5 6 public void birth(String parentName, String childName) {7 family.putIfAbsent(parentName, new ArrayList<>());8 family.get(parentName).add(childName);9 }10 11 public void death(String name) {12 dead.add(name);13 }14 15 public List<String> getInheritanceOrder() {16 List<String> ans = new ArrayList<>();17 dfs(kingName, ans);18 return ans;19 }20 21 private Set<String> dead = new HashSet<>();22 private Map<String, List<String>> family = new HashMap<>();23 private String kingName;24 25 private void dfs(final String name, List<String> ans) {26 if (!dead.contains(name))27 ans.add(name);28 if (!family.containsKey(name))29 return;30 31 for (final String child : family.get(name))32 dfs(child, ans);33 }34}35