Practice Problems on Graphs

Kathi Fisler

Here are some additional problems that you can use to practice writing traversals and working with graphs.

  1. Write a method canReach that takes a Node and returns a list of names of cities that are reachable along edges from that node. The returned list should not have any duplicates. Write down your argument for why your returned list won’t have duplicates (hint: develop invariants on the canReach method and its helper methods).

  2. During the first lecture on graphs, we mentioned different representations of graphs. One of the ones we did not choose was a list of edges, each of which contained two Nodes. Specifically:

      class CityNode {

        String name;

      }

      

      class Edge {

        CityNode source;

        CityNode target;

      }

      

      class GraphByEdges {

        LinkedList<Edge> edges;

      }

    Add a method convertToEdges to the Node class we’ve been using. The method returns a GraphByEdges with the same edges as are captured across all the connects fields of the Nodes in the original graph.

    Then, think about how you would argue that convertToEdges terminates and produces an equivalent set of edges.

  3. Do the previous problem in reverse: specifically, convert from a GraphByEdges to a graph defined through Nodes with connects fields (our standard definition). You will find it helpful to create a GraphByConnects class that contains a list of Node.