-
-
Notifications
You must be signed in to change notification settings - Fork 342
Add Depth-First Search (DFS) algorithm implementation #[HACTOBERFEST 2025] #151
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
Merged
siriak
merged 2 commits into
TheAlgorithms:master
from
piyushkumar0707:add-depth-first-search
Oct 5, 2025
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
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
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,138 @@ | ||
| # Depth-First Search (DFS) Algorithm | ||
| # | ||
| # DFS is a graph traversal algorithm that explores as far as possible along each branch | ||
| # before backtracking. It uses a stack data structure (implemented via recursion here). | ||
| # | ||
| # Time Complexity: O(V + E) where V is vertices and E is edges | ||
| # Space Complexity: O(V) for the visited array and recursion stack | ||
| # | ||
| # Input: An adjacency list representation of a graph and a starting vertex | ||
| # Output: The order in which vertices are visited during DFS traversal | ||
|
|
||
| # Recursive DFS function | ||
| dfs_recursive <- function(graph, vertex, visited, result) { | ||
| # Mark current vertex as visited | ||
| visited[vertex] <- TRUE | ||
| result <- c(result, vertex) | ||
|
|
||
| # Visit all unvisited adjacent vertices | ||
| if (vertex %in% names(graph)) { | ||
| for (neighbor in graph[[as.character(vertex)]]) { | ||
| if (!visited[neighbor]) { | ||
| result <- dfs_recursive(graph, neighbor, visited, result) | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return(result) | ||
| } | ||
piyushkumar0707 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| # Main DFS function | ||
| depth_first_search <- function(graph, start_vertex) { | ||
| # Get all vertices in the graph | ||
| all_vertices <- unique(c(names(graph), unlist(graph))) | ||
|
|
||
| # Initialize visited array | ||
| visited <- rep(FALSE, max(all_vertices)) | ||
| names(visited) <- 1:max(all_vertices) | ||
|
|
||
| # Perform DFS starting from the given vertex | ||
piyushkumar0707 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| result <- dfs_recursive(graph, start_vertex, visited, c()) | ||
|
|
||
| return(result) | ||
| } | ||
|
|
||
| # Iterative DFS function using explicit stack | ||
| dfs_iterative <- function(graph, start_vertex) { | ||
| # Get all vertices in the graph | ||
| all_vertices <- unique(c(names(graph), unlist(graph))) | ||
|
|
||
| # Initialize visited array and stack | ||
| visited <- rep(FALSE, max(all_vertices)) | ||
| names(visited) <- 1:max(all_vertices) | ||
| stack <- c(start_vertex) | ||
| result <- c() | ||
|
|
||
| while (length(stack) > 0) { | ||
| # Pop vertex from stack | ||
| vertex <- stack[length(stack)] | ||
| stack <- stack[-length(stack)] | ||
|
|
||
| if (!visited[vertex]) { | ||
| # Mark as visited and add to result | ||
| visited[vertex] <- TRUE | ||
| result <- c(result, vertex) | ||
|
|
||
| # Add all unvisited neighbors to stack (in reverse order to maintain left-to-right traversal) | ||
| if (as.character(vertex) %in% names(graph)) { | ||
| neighbors <- graph[[as.character(vertex)]] | ||
| for (neighbor in rev(neighbors)) { | ||
| if (!visited[neighbor]) { | ||
| stack <- c(stack, neighbor) | ||
| } | ||
| } | ||
| } | ||
| } | ||
| } | ||
|
|
||
| return(result) | ||
| } | ||
|
|
||
| # Example usage and testing | ||
| cat("=== Depth-First Search (DFS) Algorithm ===\n") | ||
|
|
||
| # Create a sample graph as adjacency list | ||
piyushkumar0707 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # Graph structure: | ||
| # 1 | ||
| # / \ | ||
| # 2 3 | ||
| # / \ \ | ||
| # 4 5 6 | ||
| graph <- list( | ||
| "1" = c(2, 3), | ||
| "2" = c(4, 5), | ||
| "3" = c(6), | ||
| "4" = c(), | ||
| "5" = c(), | ||
| "6" = c() | ||
| ) | ||
|
|
||
| cat("Graph structure (adjacency list):\n") | ||
| for (vertex in names(graph)) { | ||
| cat("Vertex", vertex, "-> [", paste(graph[[vertex]], collapse = ", "), "]\n") | ||
| } | ||
|
|
||
| # Test recursive DFS | ||
| cat("\nRecursive DFS starting from vertex 1:\n") | ||
| result_recursive <- depth_first_search(graph, 1) | ||
| cat("Traversal order:", paste(result_recursive, collapse = " -> "), "\n") | ||
|
|
||
| # Test iterative DFS | ||
| cat("\nIterative DFS starting from vertex 1:\n") | ||
| result_iterative <- dfs_iterative(graph, 1) | ||
| cat("Traversal order:", paste(result_iterative, collapse = " -> "), "\n") | ||
|
|
||
| # Test with different starting vertex | ||
| cat("\nRecursive DFS starting from vertex 2:\n") | ||
| result_from_2 <- depth_first_search(graph, 2) | ||
| cat("Traversal order:", paste(result_from_2, collapse = " -> "), "\n") | ||
|
|
||
| # Example with a more complex graph (with cycles) | ||
| cat("\n=== Example with Cyclic Graph ===\n") | ||
| cyclic_graph <- list( | ||
| "1" = c(2, 3), | ||
| "2" = c(1, 4), | ||
| "3" = c(1, 5), | ||
| "4" = c(2, 6), | ||
| "5" = c(3, 6), | ||
| "6" = c(4, 5) | ||
| ) | ||
|
|
||
| cat("Cyclic graph structure:\n") | ||
| for (vertex in names(cyclic_graph)) { | ||
| cat("Vertex", vertex, "-> [", paste(cyclic_graph[[vertex]], collapse = ", "), "]\n") | ||
| } | ||
|
|
||
| cat("\nDFS on cyclic graph starting from vertex 1:\n") | ||
| cyclic_result <- depth_first_search(cyclic_graph, 1) | ||
| cat("Traversal order:", paste(cyclic_result, collapse = " -> "), "\n") | ||
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.
Uh oh!
There was an error while loading. Please reload this page.