47 lines
1.2 KiB
Markdown
47 lines
1.2 KiB
Markdown
## Traversal introduction
|
|
|
|
Many algorithms that involve graphs must involve some way to traverse the elements of a graph. The two simplest ways of traversal are depth-first search (DFS) and [breadth-first search (BFS)](https://en.wikipedia.org/wiki/Breadth-first_search). The major difference here is the *order* in which nodes are traversed.
|
|
|
|
If we start from vertex 0 in the tree, in what order would you expect depth-first search to traverse the nodes? (There are multiple correct answers!)
|
|
|
|
```
|
|
0
|
|
/ \
|
|
1 2
|
|
/ \
|
|
3 4
|
|
```
|
|
|
|
Note that a single traversal step checks for already-visited nodes. So, if the path is `0 -> 1 -> 3`, the path cannot become `0 -> 1 -> 3 -> 1`.
|
|
|
|
What about starting from vertex 0 in this graph?
|
|
|
|
```
|
|
0 --- 1
|
|
| |
|
|
3 --- 2
|
|
```
|
|
|
|
What about this one?
|
|
|
|
```
|
|
0
|
|
/ \
|
|
1 5
|
|
/ \ \
|
|
2 3 6
|
|
\ / /
|
|
4 7
|
|
\ /
|
|
8
|
|
```
|
|
|
|
## Formalizing the algorithm
|
|
|
|
Based on these examples, can we create a formal algorithm that takes a starting node, producing a valid traversal path for all three graphs?
|
|
|
|
Some starter questions:
|
|
|
|
- Could recursion help us here?
|
|
- What are some ways we can track already-visited nodes? What's the most *time-efficient* way to do so?
|