|
| 1 | +# Depth-First Search |
| 2 | + |
| 3 | +Depth-first search (DFS) is an algorithm for traversing or searching [tree](../Tree/) or [graph](../Graph/) data structures. It starts at the tree source and explores as far as possible along each branch before backtracking. |
| 4 | + |
| 5 | +## The code |
| 6 | + |
| 7 | +Simple implementation of breadth-first search using a queue: |
| 8 | + |
| 9 | +```swift |
| 10 | +func depthFirstSearch(graph: Graph, source: Node) -> [String] { |
| 11 | + var nodesExplored: [String] = [source.label] |
| 12 | + source.visited = true |
| 13 | + |
| 14 | + // Iterate through all neighbors, and for each one visit all of its neighbors |
| 15 | + for edge in source.neighbors { |
| 16 | + let neighbor: Node = edge.neighbor |
| 17 | + |
| 18 | + if (!neighbor.visited) { |
| 19 | + nodesExplored += depthFirstSearch(graph, source: neighbor) |
| 20 | + } |
| 21 | + } |
| 22 | + return nodesExplored |
| 23 | +} |
| 24 | +``` |
| 25 | + |
| 26 | +Put this code in a playground and test it like so: |
| 27 | + |
| 28 | +```swift |
| 29 | +let graph = Graph() // Representing the graph from the animated example |
| 30 | + |
| 31 | +let nodeA = graph.addNode("a") |
| 32 | +let nodeB = graph.addNode("b") |
| 33 | +let nodeC = graph.addNode("c") |
| 34 | +let nodeD = graph.addNode("d") |
| 35 | +let nodeE = graph.addNode("e") |
| 36 | +let nodeF = graph.addNode("f") |
| 37 | +let nodeG = graph.addNode("g") |
| 38 | +let nodeH = graph.addNode("h") |
| 39 | + |
| 40 | +graph.addEdge(nodeA, neighbor: nodeB) |
| 41 | +graph.addEdge(nodeA, neighbor: nodeC) |
| 42 | +graph.addEdge(nodeB, neighbor: nodeD) |
| 43 | +graph.addEdge(nodeB, neighbor: nodeE) |
| 44 | +graph.addEdge(nodeC, neighbor: nodeF) |
| 45 | +graph.addEdge(nodeC, neighbor: nodeG) |
| 46 | +graph.addEdge(nodeE, neighbor: nodeH) |
| 47 | + |
| 48 | +let nodesExplored = depthFirstSearch(graph, source: nodeA) |
| 49 | +print(nodesExplored) |
| 50 | +``` |
| 51 | + |
| 52 | +This will output: `["a", "b", "d", "e", "h", "c", "f", "g"]` |
| 53 | + |
| 54 | +## Applications |
| 55 | + |
| 56 | +Depth-first search can be used to solve many problems, for example: |
| 57 | + |
| 58 | +* Finding connected components of a sparse graph |
| 59 | +* Topological sorting of nodes in a graph |
| 60 | +* Finding bridges of a graph (see: [Bridges](https://en.wikipedia.org/wiki/Bridge_(graph_theory)#Bridge-finding_algorithm)) |
| 61 | +* Among others |
0 commit comments