Zadanie 11-12 #32
PixelSculptor
started this conversation in
Zadania i rozwiązania
Replies: 1 comment
-
export interface WeightedGraph {
[key: string]: { [key: string]: number };
}
function findTheShortest(current: WeightedGraph[keyof WeightedGraph], visited: Set<string>) {
const currentEntries = Object.entries(current)
const filtered = currentEntries.filter(([key]) => !visited.has(key))
filtered.sort((a, b) => a[1] - b[1])
return filtered[0]?.[0]
}
export function findShortestPath(graph: WeightedGraph, startNode: string, endNode: string): string[] | null {
const queue = [startNode];
const result = [startNode]
const visited = new Set([startNode])
function validateRoutes() {
const routes = Object.values(graph).map(item => Object.keys(item)).flat()
routes.forEach(route => {
if (!graph[route]) {
throw new Error(`Invalid or non-existent route`)
}
})
}
validateRoutes()
while (queue.length > 0) {
const current = queue.shift()
if (typeof current !== 'string') {
break
}
const theShortest = findTheShortest(graph[current], visited)
if (theShortest) {
if (theShortest !== endNode) {
queue.push(theShortest);
}
result.push(theShortest)
visited.add(theShortest)
} else {
return null
}
}
return result
} |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Krew pot i łzy 🗡️ 😃
Beta Was this translation helpful? Give feedback.
All reactions