--- tags: Setup --- # Lecture 29 Setup/Prep Last class, we introduced the idea of checking whether a path exists between two nodes in a graph. We showed that this as a recursive process. We also showed that one could choose to visit nodes either *depth-first* (following a single path at a time deep into the graph) vs *breadth-first* (one level at a time). Today, we will look at how these two approaches differ in code. We will also discuss how to produce the returned path, rather than just report whether one exists. There is no prep, just code that we will use in class. ## Material for first in-class activity Here is the `hasRoute` code that we wrote last class. This version is recursive. ```=scala def hasRoute(from: Node, to: Node): Boolean = { // base case is that from and to are the same if (from.equals(to)) true else { // try from each next nodes for (next <- from.getsTo) { if (this.hasRoute(next, to)) return true } return false } } ``` Here is a different version that uses a separate list to track which node to visit next. This version can be written with a `while` loop: ```=scala def hasRouteChecklist(fromNode: Node, toNode: Node): Boolean = { var check = List(fromNode) while(!check.isEmpty) { val next = check.head check = check.tail if (next.equals(toNode)) return true else { check = next.getsTo ::: check } } false } ``` Our first in-class activity will have you work in groups to convince yourselves that these two approaches process the nodes in the same order. After that, we will show how to modify the second one to (a) search breadth-first, and (b) track the path that gets between the nodes.