|
| 1 | +/** |
| 2 | + * 1129. Shortest Path with Alternating Colors |
| 3 | + * https://leetcode.com/problems/shortest-path-with-alternating-colors/ |
| 4 | + * Difficulty: Medium |
| 5 | + * |
| 6 | + * You are given an integer n, the number of nodes in a directed graph where the nodes are |
| 7 | + * labeled from 0 to n - 1. Each edge is red or blue in this graph, and there could be |
| 8 | + * self-edges and parallel edges. |
| 9 | + * |
| 10 | + * You are given two arrays redEdges and blueEdges where: |
| 11 | + * - redEdges[i] = [ai, bi] indicates that there is a directed red edge from node ai |
| 12 | + * to node bi in the graph, and |
| 13 | + * - blueEdges[j] = [uj, vj] indicates that there is a directed blue edge from node uj |
| 14 | + * to node vj in the graph. |
| 15 | + * |
| 16 | + * Return an array answer of length n, where each answer[x] is the length of the shortest |
| 17 | + * path from node 0 to node x such that the edge colors alternate along the path, or -1 |
| 18 | + * if such a path does not exist. |
| 19 | + */ |
| 20 | + |
| 21 | +/** |
| 22 | + * @param {number} n |
| 23 | + * @param {number[][]} redEdges |
| 24 | + * @param {number[][]} blueEdges |
| 25 | + * @return {number[]} |
| 26 | + */ |
| 27 | +var shortestAlternatingPaths = function(n, redEdges, blueEdges) { |
| 28 | + const redGraph = Array(n).fill().map(() => new Set()); |
| 29 | + const blueGraph = Array(n).fill().map(() => new Set()); |
| 30 | + |
| 31 | + for (const [from, to] of redEdges) redGraph[from].add(to); |
| 32 | + for (const [from, to] of blueEdges) blueGraph[from].add(to); |
| 33 | + |
| 34 | + const distances = Array(n).fill().map(() => [Infinity, Infinity]); |
| 35 | + const queue = [[0, 0], [0, 1]]; |
| 36 | + distances[0] = [0, 0]; |
| 37 | + |
| 38 | + while (queue.length) { |
| 39 | + const [node, color] = queue.shift(); |
| 40 | + const nextGraph = color ? redGraph : blueGraph; |
| 41 | + const nextColor = 1 - color; |
| 42 | + |
| 43 | + for (const nextNode of nextGraph[node]) { |
| 44 | + if (distances[nextNode][nextColor] === Infinity) { |
| 45 | + distances[nextNode][nextColor] = distances[node][color] + 1; |
| 46 | + queue.push([nextNode, nextColor]); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + |
| 51 | + return distances.map(([red, blue]) => { |
| 52 | + const min = Math.min(red, blue); |
| 53 | + return min === Infinity ? -1 : min; |
| 54 | + }); |
| 55 | +}; |
0 commit comments