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

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

PowerShell: Implement Breadth First Search (BFS) on Adjacency Matrix

PowerShell

Goal -- WPM

Ready
Exercise Algorithm Area
1function Initialize-AdjacencyMatrix {
2param(
3[int]$NumVertices
4)
5
6# Create a 2D array (matrix) initialized with 0s
7$matrix = @( @(0) * $NumVertices ) * $NumVertices
8return $matrix
9}
10
11function Add-Edge {
12param(
13[int[]]$Matrix,
14[int]$Source,
15[int]$Destination,
16[int]$NumVertices
17)
18
19# Ensure indices are within bounds
20if ($Source -ge 0 -and $Source -lt $NumVertices -and $Destination -ge 0 -and $Destination -lt $NumVertices) {
21# For an undirected graph, add edge in both directions
22$Matrix[$Source][$Destination] = 1
23$Matrix[$Destination][$Source] = 1
24}
25else {
26Write-Warning "Invalid source or destination vertex."
27}
28}
29
30function Perform-BFS {
31param(
32[int[]]$AdjMatrix,
33[int]$StartNode,
34[int]$NumVertices
35)
36
37# Initialize visited array
38$visited = @( $false ) * $NumVertices
39
40# Create a queue for BFS
41$queue = New-Object System.Collections.Generic.Queue[int]
42
43# Mark the current node as visited and enqueue it
44$visited[$StartNode] = $true
45$queue.Enqueue($StartNode)
46
47# Array to store the traversal path
48$traversalPath = New-Object System.Collections.Generic.List[int]
49
50while ($queue.Count -gt 0) {
51# Dequeue a vertex from queue and print it
52$currentNode = $queue.Dequeue()
53$traversalPath.Add($currentNode)
54
55# Get all adjacent vertices of the dequeued vertex $currentNode
56# If an adjacent has not been visited, then mark it visited and enqueue it
57for ($i = 0; $i -lt $NumVertices; $i++) {
58# Check if there is an edge and if the vertex hasn't been visited
59if ($AdjMatrix[$currentNode][$i] -eq 1 -and -not $visited[$i]) {
60$visited[$i] = $true
61$queue.Enqueue($i)
62}
63}
64}
65
66return $traversalPath
67}
68
69# Example Usage:
70# $numVertices = 5
71# $adjMatrix = Initialize-AdjacencyMatrix $numVertices
72# Add-Edge $adjMatrix 0 1 $numVertices
73# Add-Edge $adjMatrix 0 2 $numVertices
74# Add-Edge $adjMatrix 1 3 $numVertices
75# Add-Edge $adjMatrix 2 4 $numVertices
76# $startNode = 0
77# $bfsPath = Perform-BFS $adjMatrix $startNode $numVertices
78# Write-Host "BFS Traversal Path: $($bfsPath -join ' -> ')"
Algorithm description viewbox

PowerShell: Implement Breadth First Search (BFS) on Adjacency Matrix

Algorithm description:

This PowerShell script implements Breadth First Search (BFS) for a graph represented by an adjacency matrix. BFS explores a graph level by level, starting from a given source node. It uses a queue to keep track of nodes to visit and a visited array to avoid revisiting nodes and getting stuck in cycles. This algorithm is useful for finding the shortest path in an unweighted graph, network broadcasting, and web crawlers.

Algorithm explanation:

The `Perform-BFS` function orchestrates the BFS traversal. It initializes a `$visited` array to keep track of visited nodes and a queue to manage the order of exploration. Starting from the `$StartNode`, it marks it as visited and enqueues it. The algorithm then enters a loop that continues as long as the queue is not empty. In each iteration, it dequeues a node, adds it to the `$traversalPath`, and then iterates through all possible neighbors (based on the adjacency matrix). If a neighbor is connected (matrix value is 1) and has not been visited, it's marked as visited and enqueued. The time complexity is O(V^2) because for each vertex, we might iterate through all V potential neighbors in the adjacency matrix. The space complexity is O(V) for storing the queue and the visited array. Edge cases include disconnected graphs, graphs with cycles, and ensuring the start node is valid.

Pseudocode:

Function Initialize-AdjacencyMatrix(NumVertices):
  matrix = 2D array of size NumVertices x NumVertices, filled with 0s
  Return matrix

Function Add-Edge(Matrix, Source, Destination, NumVertices):
  If Source and Destination are valid indices:
    Matrix[Source][Destination] = 1
    Matrix[Destination][Source] = 1 // For undirected graph

Function Perform-BFS(AdjMatrix, StartNode, NumVertices):
  visited = boolean array of size NumVertices, all false
  queue = empty queue
  visited[StartNode] = true
  queue.Enqueue(StartNode)
  traversalPath = empty list

  While queue is not empty:
    currentNode = queue.Dequeue()
    Add currentNode to traversalPath
    For i from 0 to NumVertices - 1:
      If AdjMatrix[currentNode][i] == 1 AND visited[i] is false:
        visited[i] = true
        queue.Enqueue(i)

  Return traversalPath