Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

feat: Added Kahn's Algorithm in Graphs#1804

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to ourterms of service andprivacy statement. We’ll occasionally send you account related emails.

Already on GitHub?Sign in to your account

Open
SusannaJoseph49 wants to merge1 commit intoTheAlgorithms:master
base:master
Choose a base branch
Loading
fromSusannaJoseph49:master
Open
Show file tree
Hide file tree
Changes fromall commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 63 additions & 0 deletionsGraphs/Kahn.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
/*
Source:
https://en.wikipedia.org/wiki/Topological_sorting#Kahn's_algorithm
*/

/*
Kahn's Algorithm for Topological Sorting
----------------------------------------
Works only on Directed Acyclic Graphs (DAGs).
Idea:
1. Compute indegree (number of incoming edges) for each node.
2. Start with nodes having indegree = 0 (no dependencies).
3. Repeatedly remove nodes with indegree = 0 and reduce indegree of their neighbors.
4. If all nodes are processed, we have a valid topological order.
5. If not, graph has a cycle.

Time Complexity: O(V + E) (V = vertices, E = edges)
Space Complexity: O(V + E)
*/

const KahnsAlgorithm = (numNodes, edges) => {
// Input:
// numNodes: number of vertices in the graph (0..numNodes-1)
// edges: list of directed edges [u, v] meaning u -> v
// Output:
// topoOrder: array of vertices in topological order
// OR empty array if graph contains a cycle

// Step 1: Build adjacency list and indegree array
const adj = Array.from({ length: numNodes }, () => [])
const indegree = Array(numNodes).fill(0)

for (const [u, v] of edges) {
adj[u].push(v)
indegree[v]++
}

// Step 2: Initialize queue with all nodes having indegree = 0
const queue = []
for (let i = 0; i < numNodes; i++) {
if (indegree[i] === 0) queue.push(i)
}

const topoOrder = []

// Step 3: Process queue
while (queue.length > 0) {
const node = queue.shift()
topoOrder.push(node)

for (const neighbor of adj[node]) {
indegree[neighbor]--
if (indegree[neighbor] === 0) {
queue.push(neighbor)
}
}
}

// Step 4: Verify if topological order includes all nodes
return topoOrder.length === numNodes ? topoOrder : []
}

export { KahnsAlgorithm }
55 changes: 55 additions & 0 deletionsGraphs/test/Kahn.test.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
import { KahnsAlgorithm } from '../Kahn.js'

// Check if a given order is a valid topological sort
function isValidTopologicalOrder(order, numNodes, edges) {
if (order.length !== numNodes) return false

const position = new Map()
order.forEach((node, idx) => position.set(node, idx))

for (const [u, v] of edges) {
// u must come before v in topo order
if (position.get(u) > position.get(v)) return false
}
return true
}

test('Test Case 1', () => {
const numNodes = 6
const edges = [
[5, 2],
[5, 0],
[4, 0],
[4, 1],
[2, 3],
[3, 1]
]
const topoOrder = KahnsAlgorithm(numNodes, edges)

expect(isValidTopologicalOrder(topoOrder, numNodes, edges)).toBe(true)
})

test('Test Case 2', () => {
const numNodes = 4
const edges = [
[0, 1],
[1, 2],
[2, 3]
]
const topoOrder = KahnsAlgorithm(numNodes, edges)

// Only one valid order exists
expect(topoOrder).toStrictEqual([0, 1, 2, 3])
})

test('Test Case 3 (Cycle Detection)', () => {
const numNodes = 3
const edges = [
[0, 1],
[1, 2],
[2, 0]
]
const topoOrder = KahnsAlgorithm(numNodes, edges)

expect(topoOrder).toStrictEqual([])
})

[8]ページ先頭

©2009-2025 Movatter.jp