## Answers to Self-Study Questions

- graph (a) is a connected, complete, undirected graph
- graph (b) is a connected, complete, cyclic, directed graph
- graph (c) is an unconnected, not complete, acyclic, directed graph
- graph (d) is a connected, not complete, acyclic, directed graph

For a weighted graph,
the edge weights could be stored in the nodes, with one weight for
each outgoing edge (i.e., for each successor).
So in addition to having a List of Graphnodes for the successors,
there would be a List of values;
the first value would be the label on the edge to the first successor,
the second value would be the label on the edge to the second successor,
etc.

public void resetAll() {
for (int k=0; k<nodes.size(); k++) {
((Graphnode)nodes.get(k)).setVisited(false);
}
}

#### Question 1

Every topological order must start with A, and must include both C and D
before E (but C can come before D or vice versa).
Here are some possibilities:
A B C D E
A C D E B
A C B D E
A D C B E

#### Question 2

public void topOrderAll() {
mark all nodes unvisited;
int N = nodes.size();
for each node k in the graph {
if (node k is marked unvisited) {
N = topNum(k, N);
}
}
}

#### Question 3

The solution to this question involves doing a modified depth-first
search (following both outgoing and incoming edges from any node in
the graph); the graph is connected iff all nodes are reached during
that search.
Note that the code given below iterates through ArrayLists using
the "get" method; iterators could also be used.
public boolean isConnected( ) {
if (nodes.size() == 0) return true;
// do modified dfs from some node
Graphnode n = (Graphnode)nodes.get(0);
newDfs(n);
// graph IS connected iff all nodes were visited
for (int k=0; k<nodes.size(); k++) {
n = (Graphnode)nodes.get(k);
if (!n.getVisited()) return false;
}
return true;
}
private static void newDfs(Graphnode n) {
// do a dfs but follow predecessor edges as well as successors
n.setVisited(true);
ArrayList preds = n.getPreds();
ArrayList succs = n.getSuccs();
for (int k=0; k<preds.size(); k++) {
Graphnode m = (Graphnode)preds.get(k);
if (!m.getVisited()) newDfs(m);
}
for (int k=0; k<succs.size(); k++) {
Graphnode m = (Graphnode)succs.get(k);
if (!m.getVisited()) newDfs(m);
}
}