--- tags: Setup --- # Lecture 28 Setup/Prep In this lecture, we will start our last data structure of the course: graphs! Here's an example of a graph showing (possible) bus connections within New England: ![bus routes](https://i.imgur.com/Yv6g7XQ.png) This picture has two kinds of information: cities and bus routes. Data that have some sort of item and connections between them are called graphs. By this definition, trees are graphs. But in this example, we see that there is a *cycle*, in which one can go from Boston to Providence and back again. Graphs may feature cycles (which is what makes them interesting). We refer to the items as *Nodes* and the connections as *Edges*. In this example, the edges are *directed* (meaning that we can go from Manchester to Boston, but not the other direction -- sorry, Manchester!). ## Prep We will start by choosing a data structure for graphs. Imagine that we asked you to create a data structure for holding the bus route information from the above picture. What would you use and why? ## Code to grab at right point in class :::spoiler Wait to expand this code until Kathi says so in lecture ```=scala class Graph[T] { // inner class for the node of the graph class Node(val contents: T, var getsTo: List[Node]) { // inserts outbound edge to given node def addEdge(toNode: Node) = getsTo = toNode :: getsTo override def toString = contents.toString } // a list of all the nodes in the graph private var nodes = List[Node]() def createNode(contents: T) = { val newNode = new Node(contents, List()) nodes = newNode :: nodes newNode } def addEdge(fromNode: Node, toNode: Node) = fromNode.addEdge(toNode) def show = for (node <- nodes) { println(node.contents + " gets to " + node.getsTo.toString) } } object BusRoute { val G = new Graph[String]() val bos = G.createNode("Boston") val pvd = G.createNode("Providence") val man = G.createNode("Manchester") val wor = G.createNode("Worcester") val har = G.createNode("Hartford") G.addEdge(man, bos) G.addEdge(bos, wor) G.addEdge(wor, har) G.addEdge(bos, pvd) G.addEdge(pvd, bos) } object Main extends App { BusRoute.G.show } ``` :::