-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshortestPathWithAlternatingColors.py
More file actions
35 lines (27 loc) · 1.25 KB
/
Copy pathshortestPathWithAlternatingColors.py
File metadata and controls
35 lines (27 loc) · 1.25 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
from collections import defaultdict, deque
class Solution:
def shortestAlternatingPaths(self, n: int, redEdges: list[list[int]], blueEdges: list[list[int]]) -> list[int]:
result = [10**9] * n
red_edges = defaultdict(list)
blue_edges = defaultdict(list)
for fr, to in redEdges:
red_edges[fr].append(to)
for fr, to in blueEdges:
blue_edges[fr].append(to)
visited = set()
queue = deque([(0, "any", 0)])
visited.add((0, "any"))
while queue:
current, color, cost = queue.popleft()
result[current] = min(result[current], cost)
if color in ("red", "any"):
for neighbor in blue_edges[current]:
if (neighbor, "blue") not in visited:
visited.add((neighbor, "blue"))
queue.append((neighbor, "blue", cost + 1))
if color in ("blue", "any"):
for neighbor in red_edges[current]:
if (neighbor, "red") not in visited:
visited.add((neighbor, "red"))
queue.append((neighbor, "red", cost + 1))
return [i if i != 10**9 else -1 for i in result]