Created
January 22, 2022 12:42
-
-
Save AjayPoshak/6cd473560ed429ab0d03d230f3896b37 to your computer and use it in GitHub Desktop.
This file contains 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
// This is an example of Dijkstra's algorithm. https://leetcode.com/problems/network-delay-time/ | |
function createAdjList(edges, n) { | |
const adjList = new Map() | |
for(let i=0; i<n; i++) adjList.set(i, []) | |
for(let i=0; i<edges.length; i++) { | |
const [from, to, weight] = edges[i] | |
const neighbors = adjList.get(from) | |
neighbors.push({ node: to, weight }) | |
adjList.set(from, neighbors) | |
} | |
return adjList | |
} | |
function networkDelayTime(times, n, k) { | |
const adjList = createAdjList(times, n) | |
const delayMap = new Map() | |
const visited = new Map() | |
for(let i=0; i<n; i++) delayMap.set(i, Infinity) | |
delayMap.set(k, 0) | |
findShortestPath(adjList, k, delayMap, visited, n) | |
let delayTime = 0 | |
for(let i=0; i<n; i++) { | |
if(delayMap.get(i) === Infinity) return -1 | |
delayTime = Math.max(delayTime, delayMap.get(i)) | |
} | |
return delayTime | |
} | |
function findShortestPath(adjList, currentNode, delayMap, visited, n) { | |
if(visited.has(currentNode) === true) return | |
visited.set(currentNode, true) | |
const neighbors = adjList.get(currentNode) | |
const currentDelay = delayMap.get(currentNode) | |
for(let i=0; i<neighbors.length; i++) { | |
const {node, weight} = neighbors[i] | |
if(visited.has(node) === true) continue | |
const delayAtNeighbor = delayMap.get(node) | |
const newDelay = currentDelay + weight | |
const updatedDelay = Math.min(delayAtNeighbor, newDelay) | |
delayMap.set(node, updatedDelay) | |
} | |
let min = Infinity, minNode = null | |
for(let i=0; i<n; i++) { | |
if(visited.has(i) === true) continue | |
if(delayMap.get(i) < min) { | |
min = delayMap.get(i) | |
minNode = i | |
} | |
} | |
if(minNode !== null) findShortestPath(adjList, minNode, delayMap, visited, n) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Non recursive implementation