Created
March 4, 2020 08:09
-
-
Save RP-3/6032578a4fbe924db6ccdb59b3f82155 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var shortestAlternatingPaths = function(n, red_edges, blue_edges) { | |
const reds = {}; const blues= {}; | |
red_edges.forEach(([from, to]) => { | |
reds[from] = reds[from] || new Set(); | |
reds[from].add(to); | |
}); | |
blue_edges.forEach(([from, to]) => { | |
blues[from] = blues[from] || new Set(); | |
blues[from].add(to); | |
}); | |
const result = new Array(n).fill(-1); | |
const queue = [{node: 0, red: true, dist: 0}, {node: 0, red: false, dist: 0}]; | |
const visited = new Map(); // `node:fromColour` : dist | |
while(queue.length){ | |
const {node, red, dist} = queue.shift(); | |
if(result[node] === -1) result[node] = dist; | |
if(visited.has(`${node}:${red}`)) continue; | |
visited.set(`${node}:${red}`, node); | |
const siblings = (red ? blues : reds)[node] || new Set(); | |
for(let to of siblings){ | |
if(!visited.has(`${to}:${red ? 0 : 1}`)){ | |
queue.push({node: to, red: red ? 0 : 1, dist: dist + 1}); | |
} | |
} | |
} | |
return result; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment