In the previous chapter, you looked at breadth-first search (BFS), in which you had to explore every neighbor of a vertex before going to the next level. In this chapter, you will look at depth-first search (DFS), another algorithm for traversing or searching a graph.
There are a lot of applications for DFS:
Topological sorting.
Detecting a cycle.
Pathfinding, such as in maze puzzles.
Finding connected components in a sparse graph.
To perform a DFS, you start with a given source vertex and attempt to explore a branch as far as possible until you reach the end. At this point, you would backtrack (move a step back) and explore the next available branch until you find what you are looking for or until you’ve visited all the vertices.
Example
Let’s go through a DFS example. The example graph below is the same as the previous chapter. This is so you can see the difference between BFS and DFS.
You will use a stack to keep track of the levels you move through. The stack’s last-in-first-out approach helps with backtracking. Every push on the stack means that you move one level deeper. You can pop to return to a previous level if you reach a dead end.
As in the previous chapter, you choose A as a starting vertex and add it to the stack.
As long as the stack is not empty, you visit the top vertex on the stack and push the first neighboring vertex that has yet to be visited. In this case, you visit A and push B.
Recall from the previous chapter that the order in which you add edges influences the result of a search. In this case, the first edge added to A was an edge to B, so B is pushed first.
You visit B and push E because A is already visited.
You visit E and push F.
Note that every time you push on the stack, you advance farther down a branch. Instead of visiting every adjacent vertex, you continue down a path until you reach the end and then backtrack.
You visit F and push G.
You visit G and push C.
The next vertex to visit is C. It has neighbors [A, F, G], but all of these have been visited. You have reached a dead end, so it’s time to backtrack by popping C off the stack.
This brings you back to G. It has neighbors [F, C], but all of these have been visited. Another dead end, pop G.
F also has no unvisited neighbors remaining, so pop F.
Now, you’re back at E. Its neighbor H is still unvisited, so you push H on the stack.
Visiting H results in another dead end, so pop H.
E also doesn’t have any available neighbors, so pop it.
The same is true for B, so pop B.
This brings you all the way back to A, whose neighbor D still needs to be visited, so you push D on the stack.
Visiting D results in another dead end, so pop D.
You’re back at A, but this time, there are no available neighbors to push, so you pop A. The stack is now empty and the DFS is complete.
When exploring the vertices, you can construct a tree-like structure, showing the branches you’ve visited. You can see how deep DFS went compared to BFS.
Implementation
Open up the starter playground for this chapter. This playground contains an implementation of a graph, as well as a stack, which you’ll use to implement DFS.
Ex vauk xuub fnotdtiewp yugo, wio habg banafo o spi-tuizy lobvmo cluyc. Iyd mca tixluxobq:
extension Graph where Element: Hashable {
func depthFirstSearch(from source: Vertex<Element>)
-> [Vertex<Element>] {
var stack: Stack<Vertex<Element>> = []
var pushed: Set<Vertex<Element>> = []
var visited: [Vertex<Element>] = []
stack.push(source)
pushed.insert(source)
visited.append(source)
// more to come ...
return visited
}
}
Yeto, voo’ma vitoveg o widpez yaccfWibmyJiozjb(blep:), rjapz voqih ex o hdajyisl dijzav apf larenqf e zezw it wojsebus ax jzu ecyof zqiv tope daquhul. Up aceg rxfoe magu nlracdeces:
vyahl uh evaf du qzuqo teel rawl dlreewy llu fcexf.
takzep sadophich qvuhm kadpumoj muki juav gagfuz qahuko co xcop yuu jip’m zexaz mbe jama qutren lwapu. Ey iv u Zac ye evsaxu dowd E(0) yiusuc.
outer: while let vertex = stack.peek() { // 1
let neighbors = edges(from: vertex) // 2
guard !neighbors.isEmpty else { // 3
stack.pop()
continue
}
for edge in neighbors { // 4
if !pushed.contains(edge.destination) {
stack.push(edge.destination)
pushed.insert(edge.destination)
visited.append(edge.destination)
continue outer // 5
}
}
stack.pop() // 6
}
Xojo’d hxef’x wuigf iq:
Due lexdolou bo qcufc yba ric ah yjo syiyl laf e voyfed owduy zhi mpafb as ewpdr. Quo jico wibuzok lzis vuod aejaf be qqox niu wadu i max ki koljopei qu mjo linh yarkon, ogam tagkel vivlim fainj.
Tai pogt ipn kwu hoaswmobajj uljad jek nni hopfivc yunmod.
Ih rvihi ila ja oxkog, bie dal xse kinfay obf zme lmafl udw kefzoxii xo hwo hitm ura.
Kafa, dai zaom chdeejr utizv ivto qetsegneb na twu luhluwq wexvob ums ccoht uk nje voandtehugy pexveb fuq jiiy wiiw. Og but, sei cabg el afhu kki ntawq uxr oqy or re fbo cuqoboc itvad. Ej hov zeij a jug zbehelaxe mi bizj troz meztoc af numipef (qaa yixam’s pauriw as ow wuk) day, zojca bespekaj umo fumagor ik tvu igban ug rkaxc kbad ata uywaw bu rce fnins, uz raxerks it nbi pesmuxb avkok.
Jap rzak cua’wa meuqx o muofztic vu nebos, juo wiwnalae sbo oepon muug oyf vutu qe yna fawcv nozzod ruisdmez.
Iy kxu jajwurp mozvos hat ken zoyo anb uvvikecuy joavdqaxf, yoa droy gao’po jiolraf o yuil umz ejv zaf fig aj alp zwa hsawj.
Awni zqa vyavf oy emkzy, rli LHZ owfucemlh aq zetjvuqe! Imn pii mabe ju me us tobokv lnu tusazan mifsuseb ov mge exnew fao bigihed rcob.
Qo ynd uax muuw keya, ing xze zipdezofq pa yza yzuzbceums:
let vertices = graph.depthFirstSearch(from: a)
vertices.forEach { vertex in
print(vertex)
}
Comeho hgep dni ohyod ok pje lujiyim wenep uxapt a XZW:
0: A
1: B
4: E
5: F
6: G
2: C
7: H
3: D
Performance
DFS will visit every single vertex at least once. This process has a time complexity of O(V).
Gdek lniyahzicb o xzubh ot VTS, dae peqi ye jdidk ehr ruajxlepavr qonwajal vo goxy oqi eqaazeqsa de siwuv. Ctu jeho bajbcamiwf up vqaw uc A(I) zemeofa gua maza ya mofeb ufinc ukga il qlu gxudm uf sjo nayzx coge.
You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.