Skip to content

Commit 22787b5

Browse files
authored
feat: add python solution to lc problem: No.1916 (doocs#3432)
1 parent 5ccbfdd commit 22787b5

File tree

3 files changed

+78
-2
lines changed

3 files changed

+78
-2
lines changed

solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,32 @@ tags:
8080
#### Python3
8181

8282
```python
83-
83+
class Solution:
84+
def waysToBuildRooms(self, prevRoom: List[int]) -> int:
85+
modulo = 10**9 + 7
86+
ingoing = defaultdict(set)
87+
outgoing = defaultdict(set)
88+
89+
for i in range(1, len(prevRoom)):
90+
ingoing[i].add(prevRoom[i])
91+
outgoing[prevRoom[i]].add(i)
92+
ans = [1]
93+
94+
def recurse(i):
95+
if len(outgoing[i]) == 0:
96+
return 1
97+
98+
nodes_in_tree = 0
99+
for v in outgoing[i]:
100+
cn = recurse(v)
101+
if nodes_in_tree != 0:
102+
ans[0] *= comb(nodes_in_tree + cn, cn)
103+
ans[0] %= modulo
104+
nodes_in_tree += cn
105+
return nodes_in_tree + 1
106+
107+
recurse(0)
108+
return ans[0] % modulo
84109
```
85110

86111
#### Java

solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony/README_EN.md

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,32 @@ tags:
104104
#### Python3
105105

106106
```python
107-
107+
class Solution:
108+
def waysToBuildRooms(self, prevRoom: List[int]) -> int:
109+
modulo = 10**9 + 7
110+
ingoing = defaultdict(set)
111+
outgoing = defaultdict(set)
112+
113+
for i in range(1, len(prevRoom)):
114+
ingoing[i].add(prevRoom[i])
115+
outgoing[prevRoom[i]].add(i)
116+
ans = [1]
117+
118+
def recurse(i):
119+
if len(outgoing[i]) == 0:
120+
return 1
121+
122+
nodes_in_tree = 0
123+
for v in outgoing[i]:
124+
cn = recurse(v)
125+
if nodes_in_tree != 0:
126+
ans[0] *= comb(nodes_in_tree + cn, cn)
127+
ans[0] %= modulo
128+
nodes_in_tree += cn
129+
return nodes_in_tree + 1
130+
131+
recurse(0)
132+
return ans[0] % modulo
108133
```
109134

110135
#### Java
Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
class Solution:
2+
def waysToBuildRooms(self, prevRoom: List[int]) -> int:
3+
modulo = 10**9 + 7
4+
ingoing = defaultdict(set)
5+
outgoing = defaultdict(set)
6+
7+
for i in range(1, len(prevRoom)):
8+
ingoing[i].add(prevRoom[i])
9+
outgoing[prevRoom[i]].add(i)
10+
ans = [1]
11+
12+
def recurse(i):
13+
if len(outgoing[i]) == 0:
14+
return 1
15+
16+
nodes_in_tree = 0
17+
for v in outgoing[i]:
18+
cn = recurse(v)
19+
if nodes_in_tree != 0:
20+
ans[0] *= comb(nodes_in_tree + cn, cn)
21+
ans[0] %= modulo
22+
nodes_in_tree += cn
23+
return nodes_in_tree + 1
24+
25+
recurse(0)
26+
return ans[0] % modulo

0 commit comments

Comments
 (0)