Skip to content

Commit 800d541

Browse files
authored
Create shortest-path-with-alternating-colors.py
1 parent 463fd98 commit 800d541

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
# Time: O(n + e), e is the number of red and blue edges
2+
# Space: O(n + e)
3+
4+
import collections
5+
6+
7+
class Solution(object):
8+
def shortestAlternatingPaths(self, n, red_edges, blue_edges):
9+
"""
10+
:type n: int
11+
:type red_edges: List[List[int]]
12+
:type blue_edges: List[List[int]]
13+
:rtype: List[int]
14+
"""
15+
neighbors = [[set() for _ in xrange(2)] for _ in xrange(n)]
16+
for i, j in red_edges:
17+
neighbors[i][0].add(j)
18+
for i, j in blue_edges:
19+
neighbors[i][1].add(j)
20+
INF = max(2*n-3, 0)+1
21+
dist = [[INF, INF] for i in xrange(n)]
22+
dist[0] = [0, 0]
23+
q = collections.deque([(0, 0), (0, 1)])
24+
while q:
25+
i, c = q.popleft()
26+
for j in neighbors[i][c]:
27+
if dist[j][c] != INF:
28+
continue
29+
dist[j][c] = dist[i][1^c]+1
30+
q.append((j, 1^c))
31+
return [x if x != INF else -1 for x in map(min, dist)]

0 commit comments

Comments
 (0)