File tree 3 files changed +78
-2
lines changed
solution/1900-1999/1916.Count Ways to Build Rooms in an Ant Colony
3 files changed +78
-2
lines changed Original file line number Diff line number Diff line change 80
80
#### Python3
81
81
82
82
``` 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
84
109
```
85
110
86
111
#### Java
Original file line number Diff line number Diff line change @@ -104,7 +104,32 @@ tags:
104
104
#### Python3
105
105
106
106
``` 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
108
133
```
109
134
110
135
#### Java
Original file line number Diff line number Diff line change
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
You can’t perform that action at this time.
0 commit comments