Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
25 changes: 24 additions & 1 deletion DIRECTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@
## Data Manipulation
* [Label Encode](https://github.com/TheAlgorithms/R/blob/HEAD/data_manipulation/label_encode.r)
* [One Hot Encode](https://github.com/TheAlgorithms/R/blob/HEAD/data_manipulation/one_hot_encode.r)
* [Shorten Vector](https://github.com/TheAlgorithms/R/blob/HEAD/data_manipulation/shorten.vector.R)

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

## Graph Algorithms
* [Depth First Search](https://github.com/TheAlgorithms/R/blob/HEAD/graph_algorithms/depth_first_search.r)

## Mathematics
* [Amicable Numbers](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/amicable_numbers.r)
* [Armstrong Number](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/armstrong_number.r)
Expand All @@ -42,12 +46,16 @@
* [Factorial](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/factorial.r)
* [Fibonacci](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/fibonacci.r)
* [First N Fibonacci](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/first_n_fibonacci.r)
* [Greatest Common Divisor](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/greatest_common_divisor.r)
* [Hamming Distance](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/hamming_distance.r)
* [Josephus Problem](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/josephus_problem.r)
* [Least Common Multiple](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/least_common_multiple.r)
* [Perfect Number](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/perfect_number.r)
* [Perfect Square](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/perfect_square.r)
* [Permutation Calculation](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/permutation_calculation.r)
* [Pi Monte Carlo](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/pi_monte_carlo.r)
* [Prime](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/prime.r)
* [Sieve Of Eratosthenes](https://github.com/TheAlgorithms/R/blob/HEAD/mathematics/sieve_of_eratosthenes.r)

## Regression Algorithms
* [Ann](https://github.com/TheAlgorithms/R/blob/HEAD/regression_algorithms/ann.r)
Expand Down Expand Up @@ -83,4 +91,19 @@
* [Shell Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/shell_sort.r)
* [Stooge Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/stooge_sort.r)
* [Topological Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/topological_sort.r)
* [Wiggle Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/wiggle_sort.r)
* [Wiggle Sort](https://github.com/TheAlgorithms/R/blob/HEAD/sorting_algorithms/wiggle_sort.r)

## String Manipulation
* [Find Palindrome](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/findPalindrome.R)
* [Is Anagram](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/is.anagram.R)
* [Is Lower](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/is.lower.R)
* [Is Uppercase](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/is.uppercase.R)
* [Mask Words](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/maskWords.R)
* [Rearrange Ways](https://github.com/TheAlgorithms/R/blob/HEAD/string_manipulation/rearrangeWays.R)

## Quantitative Finance
* [Kalman Filter](https://github.com/TheAlgorithms/R/blob/HEAD/quantitative_finance/kalman_filter.r)
* [Markowitz Portfolio Optimization](https://github.com/TheAlgorithms/R/blob/HEAD/quantitative_finance/markowitz_portfolio_optimization.r)
* [Monte Carlo Simulation](https://github.com/TheAlgorithms/R/blob/HEAD/quantitative_finance/monte_carlo_simulation.r)

```
138 changes: 138 additions & 0 deletions graph_algorithms/depth_first_search.r
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)
}

# 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
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
# 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")