-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathbfs-avoiding-loop.py
41 lines (28 loc) · 908 Bytes
/
bfs-avoiding-loop.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
# Time Complexity: O(n)
# Space Complexity: O(n)
import unittest
from collections import deque
from typing import List
def canReach(arr: List[int], start: int) -> bool:
n = len(arr)
q = deque()
q.append(start)
visited = {}
while len(q) > 0:
index = q.popleft()
if arr[index] == 0:
return True
for candidate in [index - arr[index], index + arr[index]]:
if 0 <= candidate <= n - 1 and candidate not in visited:
q.append(candidate)
visited[index] = True
return False
class basetest(unittest.TestCase):
def testcases1(self):
self.assertTrue(canReach([4, 2, 3, 0, 3, 1, 2], 5))
def testcases2(self):
self.assertTrue(canReach([4, 2, 3, 0, 3, 1, 2], 0))
def testcases3(self):
self.assertFalse(canReach([3, 0, 2, 1, 2], 2))
if __name__ == "__main__":
unittest.main()