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 node- aito node- bi.
- blueEdges[j] = [uj, vj]means there's a blue edge from node- ujto node- vj.
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 0is the start, so distance is0.
- Shortest path to node 1is directly from0using red edge.
- Shortest path to node 2is directly from0using blue edge.
- Shortest path to node 3is via node1using red then blue edge.
 
- Node 
Example 2:
- Input: n = 3, redEdges = [[0, 1]], blueEdges = [[2, 1]]
- Expected Output: [0, 1, -1]
- Justification:
- Node 0is the start, so distance is0.
- Shortest path to node 1is directly from0using red edge.
- Node 2is not reachable from node0with 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 0is the start, so distance is0.
- Shortest path to node 1is directly from0using red edge.
- Shortest path to node 2is via node1using red then blue edge.
- Shortest path to node 3is via node1using red edge, but not with alternative colors.
- Shortest path to node 4is via node3using 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
On this page
Problem Statement
Examples
Try it yourself