|
2 | 2 |
|
3 | 3 | Depth-first search (DFS) is an algorithm for traversing or searching [tree](../Tree/) or [graph](../Graph/) data structures. It starts at a source node and explores as far as possible along each branch before backtracking.
|
4 | 4 |
|
5 |
| -[TODO: this is a work-in-progress] |
| 5 | +Depth-first search can be used on both directed and undirected graphs. |
| 6 | + |
| 7 | +## Animated example |
| 8 | + |
| 9 | +Here's how depth-first search works on a graph: |
| 10 | + |
| 11 | + |
| 12 | + |
| 13 | +Let's say we start the search from node `A`. In depth-first search we look at the starting node's first neighbor and visit that. In the example that is node `B`. Then we look at node `B`'s first neighbor and visit it. This is node `D`. Since `D` doesn't have any unvisited neighbors of its own, we backtrack to node `B` and go to its other neighbor `E`. And so on, until we've visited all the nodes in the graph. |
| 14 | + |
| 15 | +Each time we visit the first neighbor and keep going until there's nowhere left to go, and then we backtrack to a point where there are again nodes to visit. When we've backtracked all the way to node `A`, the search is complete. |
| 16 | + |
| 17 | +For the example, the nodes were visited in the order `A`, `B`, `D`, `E`, `H`, `F`, `G`, `C`. |
| 18 | + |
| 19 | +The depth-first search process can also be visualized as a tree: |
| 20 | + |
| 21 | + |
| 22 | + |
| 23 | +The parent of a node is the one that "discovered" that node. The root of the tree is the node you started the depth-first search from. Whenever there's a branch, that's where we backtracked. |
6 | 24 |
|
7 | 25 | ## The code
|
8 | 26 |
|
@@ -45,20 +63,22 @@ graph.addEdge(nodeB, neighbor: nodeE)
|
45 | 63 | graph.addEdge(nodeC, neighbor: nodeF)
|
46 | 64 | graph.addEdge(nodeC, neighbor: nodeG)
|
47 | 65 | graph.addEdge(nodeE, neighbor: nodeH)
|
| 66 | +graph.addEdge(nodeE, neighbor: nodeF) |
| 67 | +graph.addEdge(nodeF, neighbor: nodeG) |
48 | 68 |
|
49 | 69 | let nodesExplored = depthFirstSearch(graph, source: nodeA)
|
50 | 70 | print(nodesExplored)
|
51 | 71 | ```
|
52 | 72 |
|
53 |
| -This will output: `["a", "b", "d", "e", "h", "c", "f", "g"]` |
| 73 | +This will output: `["a", "b", "d", "e", "h", "f", "g", "c"]` |
54 | 74 |
|
55 |
| -## Applications |
| 75 | +## What is DFS good for? |
56 | 76 |
|
57 | 77 | Depth-first search can be used to solve many problems, for example:
|
58 | 78 |
|
59 | 79 | * Finding connected components of a sparse graph
|
60 |
| -* Topological sorting of nodes in a graph |
| 80 | +* [Topological sorting](../Topological Sort/) of nodes in a graph |
61 | 81 | * Finding bridges of a graph (see: [Bridges](https://en.wikipedia.org/wiki/Bridge_(graph_theory)#Bridge-finding_algorithm))
|
62 | 82 | * And lots of others!
|
63 | 83 |
|
64 |
| -*Written for Swift Algorithm Club by Paulo Tanaka* |
| 84 | +*Written for Swift Algorithm Club by Paulo Tanaka and Matthijs Hollemans* |
0 commit comments