| 6 | class Solution: |
| 7 | # Time O(n) - Space O(n) |
| 8 | def minJumps(self, arr: List[int]) -> int: |
| 9 | n = len(arr) |
| 10 | # Base case. |
| 11 | if n < 2: |
| 12 | return 0 |
| 13 | # A dictionary of vertices indexed by values. |
| 14 | d = defaultdict(list) |
| 15 | for i in reversed(range(n)): |
| 16 | d[arr[i]].append(i) |
| 17 | |
| 18 | # A function that gets all neighbors of a node that we have not |
| 19 | # queued yet. |
| 20 | def getUnqueuedNeighbors(i: int) -> List[int]: |
| 21 | adj = [] |
| 22 | # We can reach the element before. |
| 23 | if 0 < i and not seen[i - 1]: |
| 24 | seen[i - 1] = True |
| 25 | adj.append(i - 1) |
| 26 | # We can reach the element after. |
| 27 | if i < n - 1 and not seen[i + 1]: |
| 28 | seen[i + 1] = True |
| 29 | adj.append(i + 1) |
| 30 | # We can also reach any element with the same value. |
| 31 | if arr[i] in d: |
| 32 | for node in d[arr[i]]: |
| 33 | if node != i: |
| 34 | adj.append(node) |
| 35 | seen[node] = True |
| 36 | d.pop(arr[i]) |
| 37 | return adj |
| 38 | |
| 39 | # A list of nodes that we have visited already. |
| 40 | seen = [False] * n |
| 41 | seen[0] = True |
| 42 | # BFS starting at 0 and counting the steps until we reach n-1. |
| 43 | steps, level = 0, deque([0]) |
| 44 | while level: |
| 45 | steps += 1 |
| 46 | # Process an entire level. |
| 47 | for _ in range(len(level)): |
| 48 | current = level.popleft() |
| 49 | for nei in getUnqueuedNeighbors(current): |
| 50 | # If this is the target node, return. |
| 51 | if nei == n - 1: |
| 52 | return steps |
| 53 | level.append(nei) |