const graph = {
0: [1, 2],
1: [3],
2: [3],
3: []
};
function kahnTopologicalSort(graph) {
const inDegree = {};
for (const node in graph) {
inDegree[node] = 0;
}
for (const node in graph) {
for (const neighbor of graph[node]) {
inDegree[neighbor]++;
}
}
const queue = [];
for (const node in inDegree) {
if (inDegree[node] === 0) queue.push(node);
}
const topoOrder = [];
while (queue.length > 0) {
const current = queue.shift();
topoOrder.push(current);
for (const neighbor of graph[current]) {
inDegree[neighbor]--;
if (inDegree[neighbor] === 0) queue.push(neighbor);
}
}
return topoOrder;
}
console.log(kahnTopologicalSort(graph));The algorithm starts with node 0 because it has zero incoming edges. Then it processes nodes 1 and 2, which become zero in-degree after removing edges from 0. Finally, node 3 is processed last.
const graph = {
0: [1],
1: [2],
2: [0]
};
function kahnTopologicalSort(graph) {
const inDegree = {};
for (const node in graph) {
inDegree[node] = 0;
}
for (const node in graph) {
for (const neighbor of graph[node]) {
inDegree[neighbor]++;
}
}
const queue = [];
for (const node in inDegree) {
if (inDegree[node] === 0) queue.push(node);
}
const topoOrder = [];
while (queue.length > 0) {
const current = queue.shift();
topoOrder.push(current);
for (const neighbor of graph[current]) {
inDegree[neighbor]--;
if (inDegree[neighbor] === 0) queue.push(neighbor);
}
}
if (topoOrder.length !== Object.keys(graph).length) {
return "Cycle detected, topological sort not possible";
}
return topoOrder;
}
console.log(kahnTopologicalSort(graph));Kahn's Algorithm cannot process all nodes because of the cycle. The queue remains empty after initialization, so the topoOrder is empty and cycle is detected.
function kahnTopologicalSort(graph) {
const inDegree = {};
for (const node in graph) {
inDegree[node] = 0;
}
for (const node in graph) {
for (const neighbor of graph[node]) {
inDegree[node]++;
}
}
const queue = [];
for (const node in inDegree) {
if (inDegree[node] === 0) queue.push(node);
}
const topoOrder = [];
while (queue.length > 0) {
const current = queue.shift();
topoOrder.push(current);
for (const neighbor of graph[current]) {
inDegree[neighbor]--;
if (inDegree[neighbor] === 0) queue.push(neighbor);
}
}
return topoOrder;
}The bug is that in-degree is incremented for 'node' instead of 'neighbor'. This causes wrong in-degree counts and incorrect topological order.
const courses = {
'Math': ['Physics'],
'Physics': ['Chemistry'],
'Chemistry': [],
'English': ['History'],
'History': []
};Courses 'English' and 'History' form one chain, and 'Math', 'Physics', 'Chemistry' form another. Both chains can be completed independently. Option A respects prerequisites order.
The queue holds nodes with zero in-degree waiting to be processed. The maximum size is the largest set of nodes that simultaneously have zero in-degree.
