Uniform Cost Priority Expansion
Identify why this UCS expands the most expensive node instead of the cheapest.
Codejavascript
function uniformCostSearch(graph, start, goal) {
const frontier = [{ node: start, cost: 0 }];
const visited = new Set();
while (frontier.length > 0) {
frontier.sort((a, b) => b.cost - a.cost);
const { node, cost } = frontier.shift();
if (node === goal) return cost;
visited.add(node);
for (const [next, w] of graph[node]) {
if (!visited.has(next)) frontier.push({ node: next, cost: cost + w });
}
}
return -1;
}This uniform-cost search returns wrong (non-optimal) paths. What is the bug?