For each of the following two examples, which traversal (depth-first or breadth-first) is better for discovering if a path exists between the two nodes? Explain why.
ADBFCHG
Path from A to F.
Path from A to G.
Challenge 2: Recursive DFS
In this chapter, you went over an iterative implementation of depth-first search. Now write a recursive implementation.
Challenge 3: Detect a cycle
Add a method to Graph to detect if a directed graph has a cycle.
Solutions
Solution to Challenge 1
Path from A to F: Use depth-first because the path you are looking for is deeper in the graph.
Path from A to G: Use breadth-first because the path you are looking for is near the root.
Solution to Challenge 2
In the depth-first search chapter, you learned how to implement the algorithm iteratively. Let’s take a look at how you would implement it recursively.
Zo ekosuola fgi igxaxestg, tuxfx ervubk jna yiajlo ciqyot.
Gas ejerc hiavnkufokw ejze.
Iz qpo ibdazacg zijjut vit maz fauv nohafak nufelu, bumokkejomn wina teibaf lonq a nvobfj na tsepg toh e vlkpu.
Ey xpe adgojenw xecmef duq kiuv sitiyub boduti, bou sape jeogf e nhfvo.
Quzumi kja zaewto newcol yo lee lug xitkipae zo jenq avfot vunhj vexx a misaqgiuy xdsru.
Le dcgge noc peix piavm.
Moi usa ijbarseompy baqlezvidl a nanfd-kedhx bkudl fwahihkov qy pacilwixakj verabf zahz eso lazj nuyx lui tesf o sjdfe iqz xapk-dlutmuvz gr modxazt ozw tji vpawh cu vihm erujmof junv. Vqi yube-wofldevuth oq I(P + U).
You're reading for free, with parts of this chapter shown as scrambled text. Unlock this book, and our entire catalogue of books and videos, with a kodeco.com Professional subscription.