-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathjump-game-iii.py
More file actions
53 lines (47 loc) · 1.62 KB
/
jump-game-iii.py
File metadata and controls
53 lines (47 loc) · 1.62 KB
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
51
52
53
from typing import List
class Solution:
# TC: O(n)
# SC: O(n)
# optimized to avoid creating auxiliary space to keep track of visited nodes
def canReach(self, arr: List[int], start: int) -> bool:
if arr[start] == 0: return True
N = len(arr)
stack = [(start, arr[start])]
arr[start] = -1
while stack:
i, d = stack.pop()
forward, backward = i+d, i-d
if forward < N and arr[forward] != -1:
if arr[forward] == 0:
return True
stack.append((forward, arr[forward]))
arr[forward] = -1
if backward >= 0 and arr[backward] != -1:
if arr[backward] == 0:
return True
stack.append((backward, arr[backward]))
arr[backward] = -1
return False
# TC: O(n)
# SC: O(n)
def canReach2(self, arr: List[int], start: int) -> bool:
if arr[start] == 0: return True
N = len(arr)
dp = [False]*(N)
dp[start] = True
stack = [(start, arr[start])]
while stack:
i, d = stack.pop()
if i + d < N and dp[d+i] == False:
ni = i + d
if arr[ni] == 0:
return True
stack.append((ni, arr[ni]))
dp[ni] = True
if i - d >= 0 and dp[i-d] == False:
ni = i - d
if arr[ni] == 0:
return True
stack.append((ni, arr[ni]))
dp[ni] = True
return False