-
Notifications
You must be signed in to change notification settings - Fork 21k
topological sort dfs #7304
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 our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
SiddhiPandey08
wants to merge
4
commits into
TheAlgorithms:master
Choose a base branch
from
SiddhiPandey08:feat/topological-sort-dfs
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.
Draft
topological sort dfs #7304
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
bceeb16
Add TopologicalSortDFS with cycle detection
SiddhiPandey08 3dde532
Add TopologicalSortDFSTest with JUnit 5 tests
SiddhiPandey08 b6d0f0e
Add TopologicalSortDFSTest with JUnit 5 tests
SiddhiPandey08 0152e2a
Fix: apply google java format
SiddhiPandey08 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
110 changes: 110 additions & 0 deletions
110
src/main/java/com/thealgorithms/datastructures/graphs/TopologicalSortDFS.java
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,110 @@ | ||
| package com.thealgorithms.datastructures.graphs; | ||
|
|
||
| import java.util.ArrayDeque; | ||
| import java.util.ArrayList; | ||
| import java.util.Deque; | ||
| import java.util.HashMap; | ||
| import java.util.List; | ||
| import java.util.Map; | ||
|
|
||
| /** | ||
| * Topological Sort using Depth-First Search (DFS). | ||
| * | ||
| * <p>A topological ordering of a directed acyclic graph (DAG) is a linear ordering | ||
| * of its vertices such that for every directed edge u → v, vertex u appears | ||
| * before vertex v in the ordering. | ||
| * | ||
| * <p>This implementation uses DFS with a 3-state visited array: | ||
| * <ul> | ||
| * <li>UNVISITED – node has not been visited yet</li> | ||
| * <li>IN_PROGRESS – node is on the current DFS path (used for cycle detection)</li> | ||
| * <li>DONE – node and all its descendants are fully processed</li> | ||
| * </ul> | ||
| * | ||
| * <p>Time Complexity: O(V + E), where V = vertices, E = edges | ||
| * Space Complexity: O(V + E) for the adjacency list and recursion stack | ||
| * | ||
| * @see <a href="https://en.wikipedia.org/wiki/Topological_sorting">Topological Sorting (Wikipedia)</a> | ||
| */ | ||
| public final class TopologicalSortDFS { | ||
|
|
||
| public TopologicalSortDFS() { | ||
| } | ||
|
|
||
| private enum VisitState { UNVISITED, IN_PROGRESS, DONE } | ||
|
|
||
| private final Map<Integer, List<Integer>> adjacencyList = new HashMap<>(); | ||
|
|
||
| /** | ||
| * Adds a directed edge from vertex {@code u} to vertex {@code v}. | ||
| * Both vertices are added to the graph if not already present. | ||
| * | ||
| * @param u the source vertex | ||
| * @param v the destination vertex | ||
| */ | ||
| public void addEdge(int u, int v) { | ||
| adjacencyList.computeIfAbsent(u, k -> new ArrayList<>()).add(v); | ||
| adjacencyList.computeIfAbsent(v, k -> new ArrayList<>()); | ||
| } | ||
|
|
||
| /** | ||
| * Adds an isolated vertex (no edges) to the graph. | ||
| * | ||
| * @param v the vertex to add | ||
| */ | ||
| public void addVertex(int v) { | ||
| adjacencyList.computeIfAbsent(v, k -> new ArrayList<>()); | ||
| } | ||
|
|
||
| /** | ||
| * Performs a topological sort of the graph using DFS. | ||
| * | ||
| * @return a {@link List} of vertices in topologically sorted order | ||
| * @throws IllegalStateException if the graph contains a cycle (i.e., is not a DAG) | ||
| */ | ||
| public List<Integer> topologicalSort() { | ||
| Map<Integer, VisitState> visitState = new HashMap<>(); | ||
| for (int vertex : adjacencyList.keySet()) { | ||
| visitState.put(vertex, VisitState.UNVISITED); | ||
| } | ||
|
|
||
| Deque<Integer> stack = new ArrayDeque<>(); | ||
|
|
||
| for (int vertex : adjacencyList.keySet()) { | ||
| if (visitState.get(vertex) == VisitState.UNVISITED) { | ||
| dfs(vertex, visitState, stack); | ||
| } | ||
| } | ||
|
|
||
| List<Integer> result = new ArrayList<>(); | ||
| while (!stack.isEmpty()) { | ||
| result.add(stack.pop()); | ||
| } | ||
| return result; | ||
| } | ||
|
|
||
| /** | ||
| * Recursive DFS helper that pushes fully processed nodes onto the stack. | ||
| * | ||
| * @param vertex the current vertex being visited | ||
| * @param visitState map tracking the visit state of each vertex | ||
| * @param stack stack accumulating vertices in reverse finish order | ||
| * @throws IllegalStateException if a back edge (cycle) is detected | ||
| */ | ||
| private void dfs(int vertex, Map<Integer, VisitState> visitState, Deque<Integer> stack) { | ||
| visitState.put(vertex, VisitState.IN_PROGRESS); | ||
|
|
||
| for (int neighbor : adjacencyList.get(vertex)) { | ||
| VisitState state = visitState.get(neighbor); | ||
| if (state == VisitState.IN_PROGRESS) { | ||
| throw new IllegalStateException("Graph contains a cycle. Topological sort is not possible."); | ||
| } | ||
| if (state == VisitState.UNVISITED) { | ||
| dfs(neighbor, visitState, stack); | ||
| } | ||
| } | ||
|
|
||
| visitState.put(vertex, VisitState.DONE); | ||
| stack.push(vertex); | ||
| } | ||
| } | ||
113 changes: 113 additions & 0 deletions
113
src/test/java/com/thealgorithms/datastructures/graphs/TopologicalSortDFSTest.java
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,113 @@ | ||
| package com.thealgorithms.datastructures.graphs; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
| import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
|
||
| import java.util.List; | ||
| import org.junit.jupiter.api.Test; | ||
|
|
||
| /** | ||
| * JUnit 5 tests for {@link TopologicalSortDFS}. | ||
| */ | ||
| class TopologicalSortDFSTest { | ||
|
|
||
| private static void assertValidTopologicalOrder(List<Integer> order, int[][] edges) { | ||
| for (int[] edge : edges) { | ||
| int u = edge[0]; | ||
| int v = edge[1]; | ||
| assertTrue(order.indexOf(u) < order.indexOf(v), "Expected " + u + " to appear before " + v + " in topological order. Got: " + order); | ||
| } | ||
| } | ||
|
|
||
| @Test | ||
| void testSimpleLinearGraph() { | ||
| TopologicalSortDFS graph = new TopologicalSortDFS(); | ||
| graph.addEdge(0, 1); | ||
| graph.addEdge(1, 2); | ||
| graph.addEdge(2, 3); | ||
|
|
||
| List<Integer> result = graph.topologicalSort(); | ||
| assertEquals(List.of(0, 1, 2, 3), result); | ||
| } | ||
|
|
||
| @Test | ||
| void testDAGWithMultiplePaths() { | ||
| // 5 → 2, 5 → 0, 4 → 0, 4 → 1, 2 → 3, 3 → 1 | ||
| TopologicalSortDFS graph = new TopologicalSortDFS(); | ||
| int[][] edges = {{5, 2}, {5, 0}, {4, 0}, {4, 1}, {2, 3}, {3, 1}}; | ||
| for (int[] edge : edges) { | ||
| graph.addEdge(edge[0], edge[1]); | ||
| } | ||
|
|
||
| List<Integer> result = graph.topologicalSort(); | ||
| assertEquals(6, result.size()); | ||
| assertValidTopologicalOrder(result, edges); | ||
| } | ||
|
|
||
| @Test | ||
| void testBuildOrderDAG() { | ||
| // 0 → 1, 0 → 2, 1 → 3, 2 → 3 | ||
| TopologicalSortDFS graph = new TopologicalSortDFS(); | ||
| int[][] edges = {{0, 1}, {0, 2}, {1, 3}, {2, 3}}; | ||
| for (int[] edge : edges) { | ||
| graph.addEdge(edge[0], edge[1]); | ||
| } | ||
|
|
||
| List<Integer> result = graph.topologicalSort(); | ||
| assertEquals(4, result.size()); | ||
| assertValidTopologicalOrder(result, edges); | ||
| } | ||
|
|
||
| @Test | ||
| void testSingleVertex() { | ||
| TopologicalSortDFS graph = new TopologicalSortDFS(); | ||
| graph.addVertex(42); | ||
|
|
||
| List<Integer> result = graph.topologicalSort(); | ||
| assertEquals(List.of(42), result); | ||
| } | ||
|
|
||
| @Test | ||
| void testDisconnectedGraph() { | ||
| TopologicalSortDFS graph = new TopologicalSortDFS(); | ||
| int[][] edges = {{0, 1}, {2, 3}}; | ||
| for (int[] edge : edges) { | ||
| graph.addEdge(edge[0], edge[1]); | ||
| } | ||
|
|
||
| List<Integer> result = graph.topologicalSort(); | ||
| assertEquals(4, result.size()); | ||
| assertValidTopologicalOrder(result, edges); | ||
| } | ||
|
|
||
| @Test | ||
| void testSimpleCycleThrowsException() { | ||
| TopologicalSortDFS graph = new TopologicalSortDFS(); | ||
| graph.addEdge(0, 1); | ||
| graph.addEdge(1, 2); | ||
| graph.addEdge(2, 0); | ||
|
|
||
| assertThrows(IllegalStateException.class, graph::topologicalSort, "Expected IllegalStateException for cyclic graph"); | ||
| } | ||
|
|
||
| @Test | ||
| void testSelfLoopThrowsException() { | ||
| TopologicalSortDFS graph = new TopologicalSortDFS(); | ||
| graph.addEdge(0, 0); | ||
|
|
||
| assertThrows(IllegalStateException.class, graph::topologicalSort, "Expected IllegalStateException for self-loop"); | ||
| } | ||
|
|
||
| @Test | ||
| void testLargerCycleThrowsException() { | ||
| TopologicalSortDFS graph = new TopologicalSortDFS(); | ||
| graph.addEdge(0, 1); | ||
| graph.addEdge(1, 2); | ||
| graph.addEdge(2, 3); | ||
| graph.addEdge(3, 4); | ||
| graph.addEdge(4, 2); | ||
|
|
||
| assertThrows(IllegalStateException.class, graph::topologicalSort, "Expected IllegalStateException for graph with cycle"); | ||
| } | ||
| } |
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Will there be some problem if we add this at the start of dfs.
If no , we can go with that as at the end we will not have to transfer elements from stack to result as we can keep array in place of stack.
If yes , will u please justify how ?