Skip to content

Commit b3d0b78

Browse files
Add Depth-First Search (DFS) algorithm (#151)
1 parent 6e76d34 commit b3d0b78

File tree

2 files changed

+162
-1
lines changed

2 files changed

+162
-1
lines changed

DIRECTORY.md

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525
## Data Manipulation
2626
* [Label Encode](https://github.com/TheAlgorithms/R/blob/HEAD/data_manipulation/label_encode.r)
2727
* [One Hot Encode](https://github.com/TheAlgorithms/R/blob/HEAD/data_manipulation/one_hot_encode.r)
28+
* [Shorten Vector](https://github.com/TheAlgorithms/R/blob/HEAD/data_manipulation/shorten.vector.R)
2829

2930
## Data Preprocessing
3031
* [Data Normalization Standardization](https://github.com/TheAlgorithms/R/blob/HEAD/data_preprocessing/data_normalization_standardization.r)
@@ -33,6 +34,9 @@
3334
* [K Folds](https://github.com/TheAlgorithms/R/blob/HEAD/data_preprocessing/k_folds.r)
3435
* [Lasso](https://github.com/TheAlgorithms/R/blob/HEAD/data_preprocessing/lasso.r)
3536

37+
## Graph Algorithms
38+
* [Depth First Search](https://github.com/TheAlgorithms/R/blob/HEAD/graph_algorithms/depth_first_search.r)
39+
3640
## Mathematics
3741
* [Amicable Numbers](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/amicable_numbers.r)
3842
* [Armstrong Number](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/armstrong_number.r)
@@ -42,12 +46,16 @@
4246
* [Factorial](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/factorial.r)
4347
* [Fibonacci](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/fibonacci.r)
4448
* [First N Fibonacci](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/first_n_fibonacci.r)
49+
* [Greatest Common Divisor](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/greatest_common_divisor.r)
4550
* [Hamming Distance](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/hamming_distance.r)
4651
* [Josephus Problem](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/josephus_problem.r)
52+
* [Least Common Multiple](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/least_common_multiple.r)
4753
* [Perfect Number](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/perfect_number.r)
4854
* [Perfect Square](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/perfect_square.r)
55+
* [Permutation Calculation](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/permutation_calculation.r)
4956
* [Pi Monte Carlo](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/pi_monte_carlo.r)
5057
* [Prime](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/prime.r)
58+
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/sieve_of_eratosthenes.r)
5159

5260
## Regression Algorithms
5361
* [Ann](https://github.com/TheAlgorithms/R/blob/HEAD/regression_algorithms/ann.r)
@@ -83,4 +91,19 @@
8391
* [Shell Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/shell_sort.r)
8492
* [Stooge Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/stooge_sort.r)
8593
* [Topological Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/topological_sort.r)
86-
* [Wiggle Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/wiggle_sort.r)
94+
* [Wiggle Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/wiggle_sort.r)
95+
96+
## String Manipulation
97+
* [Find Palindrome](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/findPalindrome.R)
98+
* [Is Anagram](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/is.anagram.R)
99+
* [Is Lower](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/is.lower.R)
100+
* [Is Uppercase](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/is.uppercase.R)
101+
* [Mask Words](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/maskWords.R)
102+
* [Rearrange Ways](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/rearrangeWays.R)
103+
104+
## Quantitative Finance
105+
* [Kalman Filter](https://github.com/TheAlgorithms/R/blob/HEAD/quantitative_finance/kalman_filter.r)
106+
* [Markowitz Portfolio Optimization](https://github.com/TheAlgorithms/R/blob/HEAD/quantitative_finance/markowitz_portfolio_optimization.r)
107+
* [Monte Carlo Simulation](https://github.com/TheAlgorithms/R/blob/HEAD/quantitative_finance/monte_carlo_simulation.r)
108+
109+
```
Lines changed: 138 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
# Depth-First Search (DFS) Algorithm
2+
#
3+
# DFS is a graph traversal algorithm that explores as far as possible along each branch
4+
# before backtracking. It uses a stack data structure (implemented via recursion here).
5+
#
6+
# Time Complexity: O(V + E) where V is vertices and E is edges
7+
# Space Complexity: O(V) for the visited array and recursion stack
8+
#
9+
# Input: An adjacency list representation of a graph and a starting vertex
10+
# Output: The order in which vertices are visited during DFS traversal
11+
12+
# Recursive DFS function
13+
dfs_recursive <- function(graph, vertex, visited, result) {
14+
# Mark current vertex as visited
15+
visited[vertex] <- TRUE
16+
result <- c(result, vertex)
17+
18+
# Visit all unvisited adjacent vertices
19+
if (vertex %in% names(graph)) {
20+
for (neighbor in graph[[as.character(vertex)]]) {
21+
if (!visited[neighbor]) {
22+
result <- dfs_recursive(graph, neighbor, visited, result)
23+
}
24+
}
25+
}
26+
27+
return(result)
28+
}
29+
30+
# Main DFS function
31+
depth_first_search <- function(graph, start_vertex) {
32+
# Get all vertices in the graph
33+
all_vertices <- unique(c(names(graph), unlist(graph)))
34+
35+
# Initialize visited array
36+
visited <- rep(FALSE, max(all_vertices))
37+
names(visited) <- 1:max(all_vertices)
38+
39+
# Perform DFS starting from the given vertex
40+
result <- dfs_recursive(graph, start_vertex, visited, c())
41+
42+
return(result)
43+
}
44+
45+
# Iterative DFS function using explicit stack
46+
dfs_iterative <- function(graph, start_vertex) {
47+
# Get all vertices in the graph
48+
all_vertices <- unique(c(names(graph), unlist(graph)))
49+
50+
# Initialize visited array and stack
51+
visited <- rep(FALSE, max(all_vertices))
52+
names(visited) <- 1:max(all_vertices)
53+
stack <- c(start_vertex)
54+
result <- c()
55+
56+
while (length(stack) > 0) {
57+
# Pop vertex from stack
58+
vertex <- stack[length(stack)]
59+
stack <- stack[-length(stack)]
60+
61+
if (!visited[vertex]) {
62+
# Mark as visited and add to result
63+
visited[vertex] <- TRUE
64+
result <- c(result, vertex)
65+
66+
# Add all unvisited neighbors to stack (in reverse order to maintain left-to-right traversal)
67+
if (as.character(vertex) %in% names(graph)) {
68+
neighbors <- graph[[as.character(vertex)]]
69+
for (neighbor in rev(neighbors)) {
70+
if (!visited[neighbor]) {
71+
stack <- c(stack, neighbor)
72+
}
73+
}
74+
}
75+
}
76+
}
77+
78+
return(result)
79+
}
80+
81+
# Example usage and testing
82+
cat("=== Depth-First Search (DFS) Algorithm ===\n")
83+
84+
# Create a sample graph as adjacency list
85+
# Graph structure:
86+
# 1
87+
# / \
88+
# 2 3
89+
# / \ \
90+
# 4 5 6
91+
graph <- list(
92+
"1" = c(2, 3),
93+
"2" = c(4, 5),
94+
"3" = c(6),
95+
"4" = c(),
96+
"5" = c(),
97+
"6" = c()
98+
)
99+
100+
cat("Graph structure (adjacency list):\n")
101+
for (vertex in names(graph)) {
102+
cat("Vertex", vertex, "-> [", paste(graph[[vertex]], collapse = ", "), "]\n")
103+
}
104+
105+
# Test recursive DFS
106+
cat("\nRecursive DFS starting from vertex 1:\n")
107+
result_recursive <- depth_first_search(graph, 1)
108+
cat("Traversal order:", paste(result_recursive, collapse = " -> "), "\n")
109+
110+
# Test iterative DFS
111+
cat("\nIterative DFS starting from vertex 1:\n")
112+
result_iterative <- dfs_iterative(graph, 1)
113+
cat("Traversal order:", paste(result_iterative, collapse = " -> "), "\n")
114+
115+
# Test with different starting vertex
116+
cat("\nRecursive DFS starting from vertex 2:\n")
117+
result_from_2 <- depth_first_search(graph, 2)
118+
cat("Traversal order:", paste(result_from_2, collapse = " -> "), "\n")
119+
120+
# Example with a more complex graph (with cycles)
121+
cat("\n=== Example with Cyclic Graph ===\n")
122+
cyclic_graph <- list(
123+
"1" = c(2, 3),
124+
"2" = c(1, 4),
125+
"3" = c(1, 5),
126+
"4" = c(2, 6),
127+
"5" = c(3, 6),
128+
"6" = c(4, 5)
129+
)
130+
131+
cat("Cyclic graph structure:\n")
132+
for (vertex in names(cyclic_graph)) {
133+
cat("Vertex", vertex, "-> [", paste(cyclic_graph[[vertex]], collapse = ", "), "]\n")
134+
}
135+
136+
cat("\nDFS on cyclic graph starting from vertex 1:\n")
137+
cyclic_result <- depth_first_search(cyclic_graph, 1)
138+
cat("Traversal order:", paste(cyclic_result, collapse = " -> "), "\n")

0 commit comments

Comments
 (0)