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

Added Kahns Algorithm#1805

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
4bhayG wants to merge2 commits intoTheAlgorithms:master
base:master
Choose a base branch
Loading
from4bhayG:Add/Kahns_Algorithm
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
65 changes: 65 additions & 0 deletionsGraphs/KahnsAlgorithm.js
View file
Open in desktop
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
import Queue from '../Data-Structures/Queue/Queue'

/**
* Author: Abhay Goel
* Implementing Kahns Algorithm for a Directed Graph
* This algorithm uses the in-degree count of a node to process
* It can be used to find Topological ordering , Cycle in a DAG.
* Tutorial on Lowest Common Ancestor: [https://www.geeksforgeeks.org/cpp/kahns-algorithm-in-cpp/](https://www.geeksforgeeks.org/cpp/kahns-algorithm-in-cpp/)
*/
export function KahnsAlgorithm(graph) {
// Keeps a track of Indegree of All Nodes in the Graph
let Indegree_of_Node = {}

/*

    Structure of Graph is like this
    Graph =>
    {
        A : [B , C] ,
        B: [C , D]
    }
u -> (v1 , v2 ..)

  */

for (const node in graph) {
// initialising empty
Indegree_of_Node[node] = 0
}

// Calculating Indeg of Nodes
for (const node in graph) {
for (const neighbor of graph[node]) {
// calculating the indegree of each node
Indegree_of_Node[neighbor] = Indegree_of_Node[neighbor] + 1
}
}

// Queue For Traversal
let queue_for_Indeg = new Queue()

// pusing all nodes
for (const node in graph) {
if (Indegree_of_Node[node] == 0) queue_for_Indeg.enqueue(node)
}

let Ordered_Nodes = []

// Algorithm starts
// loop till no nodes with are left with zero indegree
while (queue_for_Indeg.isEmpty() === false) {
let frontNode = queue_for_Indeg.peekFirst()
Ordered_Nodes.push(frontNode)
queue_for_Indeg.dequeue()

for (const neighbor of graph[frontNode]) {
Indegree_of_Node[neighbor] = Indegree_of_Node[neighbor] - 1
if (Indegree_of_Node[neighbor] === 0) {
queue_for_Indeg.enqueue(neighbor)
}
}
}

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

/**
* Helper function to verify if an array is a valid topological sort.
* For every directed edge from node U to node V, U must come before V in the sort.
* @param {object} graph - The adjacency list representation of the graph.
* @param {string[]} sortedNodes - The topologically sorted array of nodes.
* @returns {boolean} - True if the sort is valid, otherwise false.
*/
const isValidTopologicalSort = (graph, sortedNodes) => {
const nodePositions = new Map()
sortedNodes.forEach((node, index) => {
nodePositions.set(node, index)
})

for (const node in graph) {
if (!nodePositions.has(node)) {
// This can occur if a cycle is present and not all nodes are sorted.
continue
}
const u_pos = nodePositions.get(node)
for (const neighbor of graph[node]) {
// If a neighbor is missing or appears before its dependency, the sort is invalid.
if (!nodePositions.has(neighbor) || nodePositions.get(neighbor) < u_pos) {
return false
}
}
}
return true
}

describe('KahnsAlgorithm', () => {
/**
* Test Case 1: A standard Directed Acyclic Graph (DAG).
* Graph:
* 5 -> 2, 0
* 4 -> 0, 1
* 2 -> 3
* 3 -> 1
*/
test('should correctly sort a standard Directed Acyclic Graph', () => {
const graph = {
5: ['2', '0'],
4: ['0', '1'],
2: ['3'],
3: ['1'],
1: [],
0: []
}
const result = KahnsAlgorithm(graph)
// A topological sort isn't always unique, so we validate its properties.
expect(result.length).toBe(Object.keys(graph).length)
expect(isValidTopologicalSort(graph, result)).toBe(true)
})

/**
* Test Case 2: A graph with a clear cycle.
* Kahn's algorithm detects cycles by failing to process all nodes.
* Graph: A -> B -> C -> A
*/
test('should return an incomplete sort for a graph with a cycle', () => {
const graph = {
A: ['B'],
B: ['C'],
C: ['A']
}
const result = KahnsAlgorithm(graph)
// No node has an in-degree of 0, so the queue is never populated.
expect(result.length).toBeLessThan(Object.keys(graph).length)
expect(result).toEqual([])
})

/**
* Test Case 3: A disconnected graph.
* Component 1: A -> B
* Component 2: C -> D
*/
test('should correctly sort a disconnected graph', () => {
const graph = {
A: ['B'],
B: [],
C: ['D'],
D: []
}
const result = KahnsAlgorithm(graph)
expect(result.length).toBe(Object.keys(graph).length)
expect(isValidTopologicalSort(graph, result)).toBe(true)
})

/**
* Test Case 4: An empty graph.
*/
test('should return an empty array for an empty graph', () => {
const graph = {}
const result = KahnsAlgorithm(graph)
expect(result).toEqual([])
})

/**
* Test Case 5: A graph with a single node.
*/
test('should return an array with the single node for a single-node graph', () => {
const graph = { Z: [] }
const result = KahnsAlgorithm(graph)
expect(result).toEqual(['Z'])
})

/**
* Test Case 6: A cycle within a larger graph component.
* Graph: A -> B -> C -> D -> B (cycle: B-C-D)
*/
test('should handle a cycle within a larger graph', () => {
const graph = {
A: ['B'],
B: ['C'],
C: ['D'],
D: ['B']
}
const result = KahnsAlgorithm(graph)
// Only 'A' can be processed before the algorithm stops at the cycle.
expect(result.length).toBeLessThan(Object.keys(graph).length)
expect(result).toEqual(['A'])
})
})

[8]ページ先頭

©2009-2025 Movatter.jp