Graphs
Depth-First Search (Recursive)
Visit a start vertex, then recurse into its first unvisited neighbour all
the way down before backtracking. A visited set prevents revisiting, and
neighbour insertion order fixes the visit sequence.
Algorithm
Basic Implementation
basic.sh
#!/usr/bin/env bash
set -euo pipefail
declare -A adj
adj[1]="2 3"
adj[2]="1 4"
adj[3]="1 4"
adj[4]="2 3 5"
adj[5]="4 6"
adj[6]="5"
declare -A visited
order=()
dfs() {
local v=$1
visited[$v]=1
order+=("$v")
local -a nbrs
read -ra nbrs <<< "${adj[$v]}"
local nb
for nb in "${nbrs[@]}"; do
if [ -z "${visited[$nb]+_}" ]; then
dfs "$nb"
fi
done
}
dfs 1
printf '['
sep=''
for v in "${order[@]}"; do
printf '%s%d' "$sep" "$v"
sep=', '
done
printf ']\n'
Complexity
- Time: O(V + E)
- Space: O(V) recursion depth
Implementation notes
- Bash: a recursive
dfsfunction shares the globalvisitedandorderarrays; neighbours are split withread -ra. - The replay shows the current vertex, the visited set, the running visit order, and the call stack after each entry, matching the lesson spec.
recursive descent
Follow one branch to its end, then unwind and try the next neighbour.