HardNo. 1916
Count Ways to Build Rooms in an Ant Colony — LeetCode 1916 Python Solution
- Pattern
- Topological Sort
- Topics
- Tree, Graph, Topological Sort, Math, Dynamic Programming, Combinatorics
- Reading time
- 5 min
- Source
- leetcode.com
The problem
You are an ant tasked with adding n new rooms numbered 0 to n-1 to your colony. You are given the expansion plan as a 0-indexed integer array of length n, prevRoom, where prevRoom[i] indicates that you must build room prevRoom[i] before building room i, and these two rooms must be connected directly.
Example
- Input
- prevRoom = [-1,0,1]
- Output
- 1
- Explanation
- There is only one way to build the additional rooms: 0 → 1 → 2
Python solution
class Solution:
def waysToBuildRooms(self, prevRoom: List[int]) -> int:
modulo = 10**9 + 7
ingoing = defaultdict(set)
outgoing = defaultdict(set)
for i in range(1, len(prevRoom)):
ingoing[i].add(prevRoom[i])
outgoing[prevRoom[i]].add(i)
ans = [1]
def recurse(i):
if len(outgoing[i]) == 0:
return 1
nodes_in_tree = 0
for v in outgoing[i]:
cn = recurse(v)
if nodes_in_tree != 0:
ans[0] *= comb(nodes_in_tree + cn, cn)
ans[0] %= modulo
nodes_in_tree += cn
return nodes_in_tree + 1
recurse(0)
return ans[0] % moduloComplexity
- Time
- O(n·m) (typical)
- Space · auxiliary
- O(n·m)or optimized
Pattern: Topological Sort
Order a set of tasks so that every dependency comes before the thing that needs it. LeetCode 1916. Count Ways to Build Rooms in an Ant Colony is filed here because LeetCode tags it Topological Sort, which is the vocabulary this hub collects.
The topological sort guide has the Python template for the pattern and the 32 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0913 | Cat and Mouse | Hard |
| 1569 | Number of Ways to Reorder Array to Get Same BST | Hard |
| 1728 | Cat and Mouse II | Hard |
| 0062 | Unique Paths | Medium |
| 0096 | Unique Binary Search Trees | Medium |
| 0329 | Longest Increasing Path in a Matrix | Hard |
Frequently asked questions
- How hard is LeetCode 1916. Count Ways to Build Rooms in an Ant Colony?
LeetCode 1916. Count Ways to Build Rooms in an Ant Colony is rated Hard on LeetCode.
- What topics does LeetCode 1916. Count Ways to Build Rooms in an Ant Colony cover?
LeetCode 1916. Count Ways to Build Rooms in an Ant Colony is tagged Tree, Graph, Topological Sort, Math, Dynamic Programming and Combinatorics on LeetCode.