Skip to content

Commit fe8b845

Browse files
committed
Formatted Kahn's Algorithm file with Prettier
1 parent abeee9c commit fe8b845

File tree

1 file changed

+24
-17
lines changed

1 file changed

+24
-17
lines changed

Graphs/KahnsAlgorithm.js

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,41 +1,48 @@
11
// Kahn's Algorithm for Topological Sort
22
function kahnTopologicalSort(vertices, edges) {
3-
const adj = new Map();
4-
const indegree = new Array(vertices).fill(0);
3+
const adj = new Map()
4+
const indegree = new Array(vertices).fill(0)
55

66
// Build adjacency list & indegree count
77
for (let [u, v] of edges) {
8-
if (!adj.has(u)) adj.set(u, []);
9-
adj.get(u).push(v);
10-
indegree[v]++;
8+
if (!adj.has(u)) adj.set(u, [])
9+
adj.get(u).push(v)
10+
indegree[v]++
1111
}
1212

13-
const queue = [];
13+
const queue = []
1414
for (let i = 0; i < vertices; i++) {
15-
if (indegree[i] === 0) queue.push(i);
15+
if (indegree[i] === 0) queue.push(i)
1616
}
1717

18-
const topo = [];
18+
const topo = []
1919
while (queue.length > 0) {
20-
const node = queue.shift();
21-
topo.push(node);
20+
const node = queue.shift()
21+
topo.push(node)
2222

2323
if (adj.has(node)) {
2424
for (let neigh of adj.get(node)) {
25-
indegree[neigh]--;
26-
if (indegree[neigh] === 0) queue.push(neigh);
25+
indegree[neigh]--
26+
if (indegree[neigh] === 0) queue.push(neigh)
2727
}
2828
}
2929
}
3030

3131
if (topo.length !== vertices) {
32-
throw new Error("Graph has a cycle, topological sort not possible");
32+
throw new Error('Graph has a cycle, topological sort not possible')
3333
}
3434

35-
return topo;
35+
return topo
3636
}
3737

3838
// Example usage
39-
const vertices = 6;
40-
const edges = [[5,2],[5,0],[4,0],[4,1],[2,3],[3,1]];
41-
console.log("Topological Sort:", kahnTopologicalSort(vertices, edges));
39+
const vertices = 6
40+
const edges = [
41+
[5, 2],
42+
[5, 0],
43+
[4, 0],
44+
[4, 1],
45+
[2, 3],
46+
[3, 1]
47+
]
48+
console.log('Topological Sort:', kahnTopologicalSort(vertices, edges))

0 commit comments

Comments
 (0)