Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork5.7k
Added: Tarjan's SCC algorithm and test cases#1774
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
vedas-dixit wants to merge3 commits intoTheAlgorithms:masterChoose a base branch fromvedas-dixit:tarjan-strongly-connected-components
base:master
Could not load branches
Branch not found:{{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline, and old review comments may become outdated.
Uh oh!
There was an error while loading.Please reload this page.
Open
Changes fromall commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading.Please reload this page.
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
/* | ||
Tarjan's Algorithm to find all Strongly Connected Components (SCCs) in a directed graph. | ||
It performs a DFS traversal while keeping track of the discovery and low-link values | ||
to identify root nodes of SCCs. | ||
Complexity: | ||
Time: O(V + E), where V: vertices and E: edges. | ||
Space: O(V), for stack | discovery arrays | result. | ||
Reference: | ||
https://en.wikipedia.org/wiki/Tarjan%27s_strongly_connected_components_algorithm | ||
https://cp-algorithms.com/graph/strongly-connected-components.html | ||
*/ | ||
/** | ||
* Finds all strongly connected components in a directed graph using Tarjan's algorithm. | ||
* | ||
* @param {Object} graph - Directed graph represented as an adjacency list. | ||
* @returns {Array<Array<string|number>>} - List of strongly connected components (each SCC is a list of nodes). | ||
* @throws {Error} If the input graph is invalid or empty | ||
*/ | ||
function TarjanSCC(graph) { | ||
// Input validation | ||
if (!graph || typeof graph !== 'object' || Array.isArray(graph)) { | ||
throw new Error( | ||
'Graph must be a non-null object representing an adjacency list' | ||
) | ||
} | ||
if (Object.keys(graph).length === 0) { | ||
return [] | ||
} | ||
const ids = {} // Discovery time of each node | ||
const low = {} // Lowest discovery time reachable from the node | ||
const onStack = {} // To track if a node is on the recursion stack | ||
const stack = [] // Stack to hold the current path | ||
const result = [] // Array to store SCCs | ||
let time = 0 // Global timer for discovery time | ||
/** | ||
* Convert node to its proper type (number if numeric string, otherwise string) | ||
* @param {string|number} node | ||
* @returns {string|number} | ||
*/ | ||
function convertNode(node) { | ||
return !isNaN(node) && String(Number(node)) === String(node) | ||
? Number(node) | ||
: node | ||
} | ||
/** | ||
* Recursive DFS function to explore the graph and find SCCs | ||
* @param {string|number} node | ||
*/ | ||
function dfs(node) { | ||
if (!(node in graph)) { | ||
throw new Error(`Node ${node} not found in graph`) | ||
} | ||
ids[node] = low[node] = time++ | ||
stack.push(node) | ||
onStack[node] = true | ||
// Explore all neighbours | ||
const neighbors = graph[node] | ||
if (!Array.isArray(neighbors)) { | ||
throw new Error(`Neighbors of node ${node} must be an array`) | ||
} | ||
for (const neighbor of neighbors) { | ||
const convertedNeighbor = convertNode(neighbor) | ||
if (!(convertedNeighbor in ids)) { | ||
dfs(convertedNeighbor) | ||
low[node] = Math.min(low[node], low[convertedNeighbor]) | ||
} else if (onStack[convertedNeighbor]) { | ||
low[node] = Math.min(low[node], ids[convertedNeighbor]) | ||
} | ||
} | ||
// If the current node is the root of an SCC | ||
if (ids[node] === low[node]) { | ||
const scc = [] | ||
let current | ||
do { | ||
current = stack.pop() | ||
onStack[current] = false | ||
scc.push(convertNode(current)) | ||
} while (current !== node) | ||
result.push(scc) | ||
} | ||
} | ||
// Run DFS for all unvisited nodes | ||
try { | ||
for (const node in graph) { | ||
const convertedNode = convertNode(node) | ||
if (!(convertedNode in ids)) { | ||
dfs(convertedNode) | ||
} | ||
} | ||
} catch (error) { | ||
throw new Error(`Error during graph traversal: ${error.message}`) | ||
} | ||
return result | ||
} | ||
export { TarjanSCC } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,92 @@ | ||
import { TarjanSCC } from '../TarjanSCC.js' | ||
test('Test Case 1 - Simple graph with two SCCs', () => { | ||
const graph = { | ||
0: [1], | ||
1: [2], | ||
2: [0, 3], | ||
3: [4], | ||
4: [] | ||
} | ||
const result = TarjanSCC(graph) | ||
// Sort the components before comparison since order doesn't matter | ||
const expected = [[4], [3], [0, 2, 1]].map((comp) => comp.sort()) | ||
const actual = result.map((comp) => comp.sort()) | ||
expect(actual).toEqual(expect.arrayContaining(expected)) | ||
}) | ||
test('Test Case 2 - All nodes in one SCC', () => { | ||
const graph = { | ||
A: ['B'], | ||
B: ['C'], | ||
C: ['A'] | ||
} | ||
const result = TarjanSCC(graph) | ||
// Sort the components before comparison since order doesn't matter | ||
const expected = [['A', 'B', 'C']].map((comp) => comp.sort()) | ||
const actual = result.map((comp) => comp.sort()) | ||
expect(actual).toEqual(expect.arrayContaining(expected)) | ||
}) | ||
test('Test Case 3 - Disconnected nodes', () => { | ||
const graph = { | ||
1: [], | ||
2: [], | ||
3: [] | ||
} | ||
const result = TarjanSCC(graph) | ||
// Sort the components before comparison since order doesn't matter | ||
const expected = [[1], [2], [3]].map((comp) => comp.sort()) | ||
const actual = result.map((comp) => comp.sort()) | ||
expect(actual).toEqual(expect.arrayContaining(expected)) | ||
}) | ||
test('Test Case 4 - Complex Graph', () => { | ||
const graph = { | ||
0: [1], | ||
1: [2, 3], | ||
2: [0], | ||
3: [4], | ||
4: [5], | ||
5: [3] | ||
} | ||
const result = TarjanSCC(graph) | ||
// Sort the components before comparison since order doesn't matter | ||
const expected = [ | ||
[0, 2, 1], | ||
[3, 5, 4] | ||
].map((comp) => comp.sort()) | ||
const actual = result.map((comp) => comp.sort()) | ||
expect(actual).toEqual(expect.arrayContaining(expected)) | ||
}) | ||
test('Edge Case - Null input should throw error', () => { | ||
expect(() => TarjanSCC(null)).toThrow( | ||
'Graph must be a non-null object representing an adjacency list' | ||
) | ||
}) | ||
test('Edge Case - Node with non-array neighbors should throw error', () => { | ||
const graph = { | ||
A: 'not-an-array' | ||
} | ||
expect(() => TarjanSCC(graph)).toThrow('Neighbors of node A must be an array') | ||
}) | ||
test('Edge Case - Neighbor not in graph should throw error', () => { | ||
const graph = { | ||
A: ['B'] | ||
} | ||
expect(() => TarjanSCC(graph)).toThrow('Node B not found in graph') | ||
}) |
Oops, something went wrong.
Uh oh!
There was an error while loading.Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.