Problem Description
Find the shortest path from node 0 to every other node in a directed graph where edges are colored either red or blue. The path must alternate colors between consecutive edges. If no such path exists for a node, return -1 for that node.
Key Insights
- Use Breadth-First Search (BFS) to ensure the shortest path is found.
- Represent the state as a combination of the current node and the last edge color used.
- Maintain two separate adjacency lists for red and blue edges.
- Use a visited set to track (node, lastColor) combinations and avoid cycles.
- Alternate the color when selecting the next edges in the BFS.
Space and Time Complexity
Time Complexity: O(n + r + b) where n is the number of nodes and r and b are the numbers of red and blue edges, since each state (node with a particular color) is processed once. Space Complexity: O(n + r + b) due to storage of the graph and the visited states used for BFS.
Solution
Use a BFS approach where each queue element contains the node, the distance from the start (node 0), and the last color of the edge that was used to reach this node. Maintain two graphs for red and blue edges. For every node, try to traverse the edges of the opposite color from the color used in the previous step. Mark combinations of nodes and colors as visited to prevent reprocessing. Update the answer array for each node with the smallest number of edges found that satisfy the alternating color requirement.