Skip to content

Commit 0dcbb33

Browse files
authored
Create count-all-possible-routes.py
1 parent ae3c90d commit 0dcbb33

File tree

1 file changed

+66
-0
lines changed

1 file changed

+66
-0
lines changed

Python/count-all-possible-routes.py

Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
# Time: O(nlogn + n * f)
2+
# Space: O(n * f)
3+
4+
import bisect
5+
6+
7+
class Solution(object):
8+
def countRoutes(self, locations, start, finish, fuel):
9+
"""
10+
:type locations: List[int]
11+
:type start: int
12+
:type finish: int
13+
:type fuel: int
14+
:rtype: int
15+
"""
16+
MOD = 10**9+7
17+
18+
s, f = locations[start], locations[finish];
19+
locations.sort()
20+
start, finish = bisect.bisect_left(locations, s), bisect.bisect_left(locations, f)
21+
22+
left = [[0]*(fuel+1) for _ in xrange(len(locations))] # left[i][f], last move is toward left to location i by f fuel
23+
right = [[0]*(fuel+1) for _ in xrange(len(locations))] # right[i][f], last move is toward right to location i by f fuel
24+
for f in xrange(1, fuel+1):
25+
for j in xrange(len(locations)-1):
26+
d = locations[j+1]-locations[j]
27+
if f > d:
28+
left[j][f] = (right[j+1][f-d] + 2*left[j+1][f-d] % MOD) % MOD;
29+
elif f == d:
30+
left[j][f] = int(j+1 == start)
31+
for j in xrange(1, len(locations)):
32+
d = locations[j]-locations[j-1]
33+
if f > d:
34+
right[j][f] = (left[j-1][f-d] + 2*right[j-1][f-d] % MOD) % MOD
35+
elif f == d:
36+
right[j][f] = int(j-1 == start)
37+
result = int(start == finish)
38+
for f in xrange(1, fuel+1):
39+
result = ((result + left[finish][f]) % MOD + right[finish][f]) % MOD
40+
return result
41+
42+
43+
# Time: O(n^2 * f)
44+
# Space: O(n * f)
45+
class Solution2(object):
46+
def countRoutes(self, locations, start, finish, fuel):
47+
"""
48+
:type locations: List[int]
49+
:type start: int
50+
:type finish: int
51+
:type fuel: int
52+
:rtype: int
53+
"""
54+
MOD = 10**9+7
55+
dp = [[0]*(fuel+1) for _ in xrange(len(locations))]
56+
dp[start][0] = 1
57+
for f in xrange(fuel+1):
58+
for i in xrange(len(locations)):
59+
for j in xrange(len(locations)):
60+
if i == j:
61+
continue
62+
d = abs(locations[i]-locations[j])
63+
if f-d < 0:
64+
continue
65+
dp[i][f] = (dp[i][f]+dp[j][f-d])%MOD
66+
return reduce(lambda x, y: (x+y)%MOD, dp[finish])

0 commit comments

Comments
 (0)