Here is a simple implementation of Depth First Search (DFS) for a graph in Swift using recursion:
main.swift932 chars47 lines
In this implementation, we start with a graph defined as an adjacency list (adjList
) and a visited
array that keeps track of whether a given vertex has been visited during the DFS traversal.
The addEdge
function adds edges to the graph by adding an adjacent vertex to the list of neighbors for a given vertex.
The dfs
function performs the actual DFS traversal. We start by marking the current node as visited and printing it. Then, for each neighbor of the current node, we recursively call the dfs
function if it hasn't already been visited.
The dfsTraversal
function initializes the visited
array and starts the DFS traversal from a given starting node.
Finally, we create a Graph
instance, add edges to it, and perform a DFS traversal starting from node 2. When we run this code, the output should be:
main.swift8 chars5 lines
indicating that the nodes were visited in the order 2, 0, 1, 3.
gistlibby LogSnag