Generation

generate functionMon, 10 Apr 2023

Find a shortest path from one dot to another ib non oriented graph

function shortestPath(graph: Graph, fromIndex: number, toIndex: number) { const queue = [fromIndex] const visited = [] const previous = [] while (queue.length > 0) { const next = queue.splice(0, 1)[0] visited.push(next) if (next === toIndex) { const path = [next] while (next !== fromIndex) { next = previous[next] path.push(next) } return path } graph[next].forEach(neighbour => { if (visited.includes(neighbour)) { return } previous[neighbour] = next queue.push(neighbour) }) } }

TypeScript
Generate More

Questions about programming?Chat with your personal AI assistant