-
Notifications
You must be signed in to change notification settings - Fork 0
/
55. Jump Game.py
50 lines (28 loc) · 1.31 KB
/
55. Jump Game.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
class Solution:
#approach 1: backtracking
#we try every single jump pattern that takes us from the first position to the last. We start from the first position and jump to every index that is reachable. We repeat the process until last index is reached. When stuck, backtrack.
def canJumpFromPosition(self, position, nums):
if (position == len(nums) - 1 ):
return True
furthest = min(position + nums[position], len(nums) - 1)
for nextposition in range(position+1, furthest):
if (canJumpFromPosition(nextposition,nums)== True):
return True
def canJump(nums):
return canJumpFromPosition(0, nums)
#approach 2:
#solve it as a graph problem
#using dfs
def canJump(self, nums):
visited , stack = set(), [0]
while stack:
position = stack.pop()
print(position)
if position >= len(nums) - 1 :
return True
maxposition = min(position + nums[position], len(nums)-1)
for i in range(position+1, maxposition+1):
if i not in visited:
visited.add(i)
stack.append(i)
return False