Text: Programming: Directed Graphs
We say that a graph is 2-colorable if there is a way to label each node with a color in such a way that no node is adjacent to another of the same color. That is, the colors alternate. Implement a recursive method to check if an undirected graph is 2-colorable and generate labels for the graph. Use the method signature below (Note: using recursion means you won't need to create a stack variable in your code). Assume that you are using the standard Digraph ADT discussed in class and have the marked and color globals available. If you need more globals, please indicate them.
public class Digraph {
Digraph(int V) // create a V-vertex digraph with no edges
Digraph(In Sn) // read a digraph from input stream fn
int V() // number of vertices
int E() // number of edges
void addEdge(int v, int w) // add edge v->w to this digraph
Iterable<Integer> adj(int v) // vertices connected to v by edges pointing from v
Digraph reverse() // reverse of this digraph
String toString() // string representation
}
enum Color {RED, GREEN, UNLABELED}
boolean[] marked;
private[] color;
bool isTwoColorable(Digraph G) {
// start algorithm by beginning at node 0 and coloring it RED
if (isTwoColorable(G, 0, Color.RED)) {
return colors; // returns the coloring of the nodes if the graph is two colorable
} else {
return null; // indicates graph is not two colorable
}
}
bool isTwoColorable(Digraph G, int v, Color c) {
// TODO: IMPLEMENT ME
}
HTMLEdit
IYA.A.I C
X
T