ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

PowerShell: Implement Depth First Search (DFS) on Adjacency List

PowerShell

Goal -- WPM

Ready
Exercise Algorithm Area
1function Get-GraphAdjacencyList {
2param(
3[hashtable]$GraphData
4)
5
6$adjList = @{}
7foreach ($node in $GraphData.Keys) {
8$adjList[$node] = @()
9}
10
11foreach ($edge in $GraphData.Values) {
12$fromNode = $edge.From
13$toNode = $edge.To
14$adjList[$fromNode] += $toNode
15# For undirected graphs, add the reverse edge too
16# $adjList[$toNode] += $fromNode
17}
18return $adjList
19}
20
21function DFS-Recursive {
22param(
23[hashtable]$AdjList,
24[string]$StartNode,
25[hashtable]$Visited,
26[System.Collections.Generic.List[string]]$TraversalPath
27)
28
29# Mark the current node as visited
30$Visited[$StartNode] = $true
31$TraversalPath.Add($StartNode)
32
33# Recur for all the vertices adjacent to this vertex
34if ($AdjList.ContainsKey($StartNode)) {
35foreach ($neighbor in $AdjList[$StartNode]) {
36if (-not $Visited.ContainsKey($neighbor) -or $Visited[$neighbor] -eq $false) {
37DFS-Recursive $AdjList $neighbor $Visited $TraversalPath
38}
39}
40}
41}
42
43function Perform-DFS {
44param(
45[hashtable]$GraphData,
46[string]$StartNode
47)
48
49# Build adjacency list from graph data
50$adjList = Get-GraphAdjacencyList $GraphData
51
52# Initialize visited set and traversal path
53$Visited = @{}
54$TraversalPath = New-Object System.Collections.Generic.List[string]
55
56# Check if start node exists in the graph
57if (-not $adjList.ContainsKey($StartNode)) {
58Write-Warning "Start node '$StartNode' not found in the graph."
59return $null
60}
61
62# Perform DFS starting from the given node
63DFS-Recursive $adjList $StartNode $Visited $TraversalPath
64
65# Return the path of traversal
66return $TraversalPath
67}
68
69# Example Usage:
70# $graph = @{
71# 'A' = @{From='A'; To='B'}
72# 'B' = @{From='B'; To='C'}
73# 'C' = @{From='C'; To='D'}
74# 'D' = @{From='D'; To='A'}
75# 'E' = @{From='E'; To='F'}
76# }
77# $start = 'A'
78# $dfsPath = Perform-DFS $graph $start
79# Write-Host "DFS Traversal Path: $($dfsPath -join ' -> ')"
Algorithm description viewbox

PowerShell: Implement Depth First Search (DFS) on Adjacency List

Algorithm description:

This PowerShell script implements Depth First Search (DFS) for a graph represented by an adjacency list. It explores as far as possible along each branch before backtracking. The script includes a helper function for the recursive traversal and handles graph construction from a simple data structure. DFS is fundamental for tasks like finding connected components, topological sorting, and solving puzzles like mazes.

Algorithm explanation:

The `Perform-DFS` function orchestrates the DFS process. It first constructs an adjacency list from the provided graph data using `Get-GraphAdjacencyList`. Then, it initializes a hashtable `$Visited` to keep track of visited nodes and a generic list `$TraversalPath` to record the order of visited nodes. The core logic resides in `DFS-Recursive`, which marks the current node as visited, adds it to the path, and then recursively calls itself for each unvisited neighbor. This ensures that the algorithm explores deeply along one path before exploring alternatives. The time complexity is O(V + E), where V is the number of vertices and E is the number of edges, as each vertex and edge is visited at most once. The space complexity is O(V) in the worst case due to the recursion depth and the storage for visited nodes and the traversal path. Edge cases include disconnected graphs, graphs with cycles, and ensuring the start node exists.

Pseudocode:

Function Get-GraphAdjacencyList(GraphData):
  adjList = empty hash table
  For each node in GraphData keys:
    adjList[node] = empty array
  For each edge in GraphData values:
    fromNode = edge.From
    toNode = edge.To
    Add toNode to adjList[fromNode]
  Return adjList

Function DFS-Recursive(AdjList, StartNode, Visited, TraversalPath):
  Mark StartNode as visited in Visited
  Add StartNode to TraversalPath
  If StartNode has neighbors in AdjList:
    For each neighbor of StartNode:
      If neighbor is not visited:
        DFS-Recursive(AdjList, neighbor, Visited, TraversalPath)

Function Perform-DFS(GraphData, StartNode):
  adjList = Get-GraphAdjacencyList(GraphData)
  Visited = empty hash table
  TraversalPath = empty list
  If StartNode is not in adjList:
    Return null
  DFS-Recursive(adjList, StartNode, Visited, TraversalPath)
  Return TraversalPath