Medium
,BFS
,Graph
1129. Shortest Path with Alternating Colors
You are given an integer n
, the number of nodes in a directed graph where the nodes are labeled from 0
to n - 1
. Each edge is red or blue in this graph, and there could be self-edges and parallel edges.
You are given two arrays redEdges
and blueEdges
where:
redEdges[i]
= [ai, bi]
indicates that there is a directed red edge from node ai
to node bi
in the graph, andblueEdges[j]
= [uj, vj]
indicates that there is a directed blue edge from node uj
to node vj
in the graph.Return an array answer
of length n
, where each answer[x]
is the length of the shortest path from node 0
to node x
such that the edge colors alternate along the path, or -1
if such a path does not exist.
Example 1:
Example 2:
Constraints:
n
<= 100redEdges.length
, blueEdges.length
<= 400redEdges[i].length
== blueEdges[j].length
== 2ai
, bi
, uj
, vj
< n
Time: e
為紅藍edge總數, 每個點最多被拜訪兩次, 每個點最多走紅藍兩次edge
Extra Space: Adjacency list儲存e
個edge, BFS queue最多儲存n
個node
XD Feb 11, 2023
graph[u] = {v, color}
v
改成-1,使其不會被重複使用Yen-Chi ChenSat, Feb 11, 2023
MarsgoatFeb 20, 2023