Leetcode 1129: Shortest Path with Alternating Colors

grid47
grid47
Exploring patterns and algorithms
Jul 17, 2024 8 min read

You are given a directed graph with n nodes, where each node is labeled from 0 to n-1. The graph contains edges that can be either red or blue. You are provided with two lists of edges: redEdges and blueEdges, where redEdges[i] = [ai, bi] indicates a directed red edge from node ai to node bi, and blueEdges[j] = [uj, vj] indicates a directed blue edge from node uj to node vj. Your goal is to find the shortest alternating path from node 0 to each node x. Return an array answer where each answer[x] is the length of the shortest alternating path from node 0 to node x, or -1 if no such path exists.
Problem
Approach
Steps
Complexity
Input: You are given two arrays representing red and blue edges in a directed graph. Each array consists of pairs of integers denoting the start and end nodes of the respective colored edges.
Example: Input: n = 4, redEdges = [[0,1],[1,2]], blueEdges = [[2,3]]
Constraints:
• 1 <= n <= 100
• 0 <= redEdges.length, blueEdges.length <= 400
• redEdges[i].length == blueEdges[j].length == 2
• 0 <= ai, bi, uj, vj < n
Output: Return an array answer where answer[x] is the length of the shortest alternating path from node 0 to node x, or -1 if no such path exists.
Example: Output: [0, 1, 2, 3]
Constraints:
• The array should have length n.
• The value of each element should be either the shortest path length or -1 if no path exists.
Goal: The goal is to compute the shortest alternating paths from node 0 to all other nodes, alternating between red and blue edges.
Steps:
• Initialize a graph representation with two colors (red and blue).
• Use a BFS (Breadth-First Search) to explore the graph, alternating between red and blue edges.
• Track the shortest path to each node for both edge colors and ensure the paths alternate.
Goal: Ensure the solution works efficiently for the maximum constraint sizes.
Steps:
• The input graph will have up to 100 nodes.
• There can be up to 400 red and blue edges each.
Assumptions:
• The graph may contain self-loops and parallel edges.
• The input will always be valid according to the given constraints.
Input: Input: n = 4, redEdges = [[0,1],[1,2]], blueEdges = [[2,3]]
Explanation: Starting from node 0, we first move to node 1 with a red edge, then to node 2 with a blue edge, and finally to node 3 with a red edge. This gives us the shortest alternating path to each node.

Input: Input: n = 3, redEdges = [[0,1]], blueEdges = [[2,1]]
Explanation: Starting from node 0, we can reach node 1 with a red edge, but node 2 is not reachable with an alternating path, so the answer for node 2 is -1.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus