Back to course home
0% completed
Vote For New Content
Shortest Path with Alternating Colors (medium)
Problem Statement
You have a directed graph with n
nodes labeled from 0
to n-1
. The graph has two types of edges: red and blue. You are given two arrays redEdges
and blueEdges
:
redEdges[i] = [ai, bi]
means there's a red edge from nodeai
to nodebi
.blueEdges[j] = [uj, vj]
means there's a blue edge from nodeuj
to nodevj
.
Find the shortest path from node 0
to each node x
such that the edges alternate in colors. If there is no such path, return -1
for that node.
Return an array answer
of length n
, where answer[x]
is the length of the shortest alternating path from node 0
to node x
.
Examples
Example 1:
- Input: n = 4, redEdges = [[0, 1], [1, 2], [2, 3]], blueEdges = [[0, 2], [2, 1], [1, 3]]
- Expected Output: [0, 1, 1, 2]
- Justification:
- Node
0
is the start, so distance is0
. - Shortest path to node
1
is directly from0
using red edge. - Shortest path to node
2
is directly from0
using blue edge. - Shortest path to node
3
is via node1
using red then blue edge.
- Node
Example 2:
- Input: n = 3, redEdges = [[0, 1]], blueEdges = [[2, 1]]
- Expected Output: [0, 1, -1]
- Justification:
- Node
0
is the start, so distance is0
. - Shortest path to node
1
is directly from0
using red edge. - Node
2
is not reachable from node0
with alternating colors.
- Node
Example 3:
- Input: n = 5, redEdges = [[0, 1], [1, 3]], blueEdges = [[1, 2], [3, 4]]
- Expected Output: [0, 1, 2, -1, -1]
- Justification:
- Node
0
is the start, so distance is0
. - Shortest path to node
1
is directly from0
using red edge. - Shortest path to node
2
is via node1
using red then blue edge. - Shortest path to node
3
is via node1
using red edge, but not with alternative colors. - Shortest path to node
4
is via node3
using red then blue edge, but not with alternative colors.
- Node
Constraints:
- 1 <= n <= 100
- 0 <= redEdges.length, blueEdges.length <= 400
- redEdges[i].length == blueEdges[j].length == 2
- 0 <= ai, bi, uj, vj < n
Try it yourself
Try solving this question here:
Python3
Python3
. . . .
Mark as Completed
Table of Contents
Problem Statement
Examples
Try it yourself