Complete the implementation of the Weighted Graph that we began in this chapter by provide
bodies for the methods isEmpty, isFull, hasVertex, clearMarks, markVertex, isMarked, and
getUnmarked in the WeightedGraph.java file. Test the completed implementation using the
UseGraph class. When implementing hasVertex, dont forget to use the equals mehtod to
compare vertices. Java Code.
// Incomplete version
//----------------------------------------------------------------------------
// WeightedGraph.java by Dale/Joyce/Weems Chapter 9
//
// Implements a directed graph with weighted edges.
// Vertices are objects of class T and can be marked as having been visited.
// Edge weights are integers.
// Equivalence of vertices is determined by the vertices\' equals method.
//
// General precondition: Except for the addVertex and hasVertex methods,
// any vertex passed as an argument to a method is in this graph.
//----------------------------------------------------------------------------
package ch09.graphs;
import ch05.queues.*;
public class WeightedGraph implements WeightedGraphInterface
{
public static final int NULL_EDGE = 0;
private static final int DEFCAP = 50; // default capacity
private int numVertices;
private int maxVertices;
private T[] vertices;
private int[][] edges;
private boolean[] marks; // marks[i] is mark for vertices[i]
public WeightedGraph()
// Instantiates a graph with capacity DEFCAP vertices.
{
numVertices = 0;
maxVertices = DEFCAP;
vertices = (T[]) new Object[DEFCAP];
marks = new boolean[DEFCAP];
edges = new int[DEFCAP][DEFCAP];
}
public WeightedGraph(int maxV)
// Instantiates a graph with capacity maxV.
{
numVertices = 0;
maxVertices = maxV;
vertices = (T[]) new Object[maxV];
marks = new boolean[maxV];
edges = new int[maxV][maxV];
}
public boolean isEmpty()
// Returns true if this graph is empty; otherwise, returns false.
{
}
public boolean isFull()
// Returns true if this graph is full; otherwise, returns false.
{
}
public void addVertex(T vertex)
// Preconditions: This graph is not full.
// Vertex is not already in this graph.
// Vertex is not null.
//
// Adds vertex to this graph.
{
vertices[numVertices] = vertex;
for (int index = 0; index < numVertices; index++)
{
edges[numVertices][index] = NULL_EDGE;
edges[index][numVertices] = NULL_EDGE;
}
numVertices++;
}
public boolean hasVertex(T vertex)
// Returns true if this graph contains vertex; otherwise, returns false.
{
}
private int indexIs(T vertex)
// Returns the index of vertex in vertices.
{
int index = 0;
while (!vertex.equals(vertices[index]))
index++;
return index;
}
public void addEdge(T fromVertex, T toVertex, int weight)
// Adds an edge with the specified weight from fromVertex to toVertex.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
edges[row][column] = weight;
}
public int weightIs(T fromVertex, T toVertex)
// If edge from fromVertex to toVertex exists, returns the weight of edge;
// otherwise, returns a special “null-edge” value..
Complete the implementation of the Weighted Graph that we began in t.pdf
1. Complete the implementation of the Weighted Graph that we began in this chapter by provide
bodies for the methods isEmpty, isFull, hasVertex, clearMarks, markVertex, isMarked, and
getUnmarked in the WeightedGraph.java file. Test the completed implementation using the
UseGraph class. When implementing hasVertex, dont forget to use the equals mehtod to
compare vertices. Java Code.
// Incomplete version
//----------------------------------------------------------------------------
// WeightedGraph.java by Dale/Joyce/Weems Chapter 9
//
// Implements a directed graph with weighted edges.
// Vertices are objects of class T and can be marked as having been visited.
// Edge weights are integers.
// Equivalence of vertices is determined by the vertices' equals method.
//
// General precondition: Except for the addVertex and hasVertex methods,
// any vertex passed as an argument to a method is in this graph.
//----------------------------------------------------------------------------
package ch09.graphs;
import ch05.queues.*;
public class WeightedGraph implements WeightedGraphInterface
{
public static final int NULL_EDGE = 0;
private static final int DEFCAP = 50; // default capacity
private int numVertices;
private int maxVertices;
private T[] vertices;
private int[][] edges;
private boolean[] marks; // marks[i] is mark for vertices[i]
public WeightedGraph()
// Instantiates a graph with capacity DEFCAP vertices.
{
numVertices = 0;
maxVertices = DEFCAP;
vertices = (T[]) new Object[DEFCAP];
marks = new boolean[DEFCAP];
2. edges = new int[DEFCAP][DEFCAP];
}
public WeightedGraph(int maxV)
// Instantiates a graph with capacity maxV.
{
numVertices = 0;
maxVertices = maxV;
vertices = (T[]) new Object[maxV];
marks = new boolean[maxV];
edges = new int[maxV][maxV];
}
public boolean isEmpty()
// Returns true if this graph is empty; otherwise, returns false.
{
}
public boolean isFull()
// Returns true if this graph is full; otherwise, returns false.
{
}
public void addVertex(T vertex)
// Preconditions: This graph is not full.
// Vertex is not already in this graph.
// Vertex is not null.
//
// Adds vertex to this graph.
{
vertices[numVertices] = vertex;
for (int index = 0; index < numVertices; index++)
{
edges[numVertices][index] = NULL_EDGE;
edges[index][numVertices] = NULL_EDGE;
}
numVertices++;
}
public boolean hasVertex(T vertex)
3. // Returns true if this graph contains vertex; otherwise, returns false.
{
}
private int indexIs(T vertex)
// Returns the index of vertex in vertices.
{
int index = 0;
while (!vertex.equals(vertices[index]))
index++;
return index;
}
public void addEdge(T fromVertex, T toVertex, int weight)
// Adds an edge with the specified weight from fromVertex to toVertex.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
edges[row][column] = weight;
}
public int weightIs(T fromVertex, T toVertex)
// If edge from fromVertex to toVertex exists, returns the weight of edge;
// otherwise, returns a special “null-edge” value.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
return edges[row][column];
}
public UnboundedQueueInterface getToVertices(T vertex)
// Returns a queue of the vertices that are adjacent from vertex.
{
4. UnboundedQueueInterface adjVertices = new LinkedUnbndQueue();
int fromIndex;
int toIndex;
fromIndex = indexIs(vertex);
for (toIndex = 0; toIndex < numVertices; toIndex++)
if (edges[fromIndex][toIndex] != NULL_EDGE)
adjVertices.enqueue(vertices[toIndex]);
return adjVertices;
}
public void clearMarks()
// Sets marks for all vertices to false.
{
}
public void markVertex(T vertex)
// Sets mark for vertex to true.
{
}
public boolean isMarked(T vertex)
// Returns true if vertex is marked; otherwise, returns false.
{
}
public T getUnmarked()
// Returns an unmarked vertex if any exist; otherwise, returns null.
{
}
}
//----------------------------------------------------------------------------
// UseGraph.java by Dale/Joyce/Weems Chapter 9
//
// Examples of uses of the Graph ADT.
//----------------------------------------------------------------------------
import ch05.queues.*;
import ch03.stacks.*;
import answers.ch09.graphs.*; // remove answers.
import ch09.priorityQueues.*;
5. import support.Flight;
public class UseGraph
{
private static void shortestPaths(WeightedGraphInterface graph,
String startVertex )
// Writes the shortest distance from startVertex to every
// other reachable vertex in graph.
{
Flight flight;
Flight saveFlight; // for saving on priority queue
int minDistance;
int newDistance;
PriQueueInterface pq = new Heap(20); // Assume at most 20 vertices
String vertex;
UnboundedQueueInterface vertexQueue = new LinkedUnbndQueue();
graph.clearMarks();
saveFlight = new Flight(startVertex, startVertex, 0);
pq.enqueue(saveFlight);
System.out.println("Last Vertex Destination Distance");
System.out.println("------------------------------------");
do
{
flight = pq.dequeue();
if (!graph.isMarked(flight.getToVertex()))
{
graph.markVertex(flight.getToVertex());
System.out.println(flight);
flight.setFromVertex(flight.getToVertex());
minDistance = flight.getDistance();
vertexQueue = graph.getToVertices(flight.getFromVertex());
while (!vertexQueue.isEmpty())
{
vertex = vertexQueue.dequeue();
if (!graph.isMarked(vertex))
6. {
newDistance = minDistance
+ graph.weightIs(flight.getFromVertex(), vertex);
saveFlight = new Flight(flight.getFromVertex(), vertex, newDistance);
pq.enqueue(saveFlight);
}
}
}
} while (!pq.isEmpty());
System.out.println();
System.out.println("The unreachable vertices are:");
vertex = graph.getUnmarked();
while (vertex != null)
{
System.out.println(vertex);
graph.markVertex(vertex);
vertex = graph.getUnmarked();
}
System.out.println();
}
private static boolean isPath(WeightedGraphInterface graph,
String startVertex,
String endVertex )
// Returns true if a path exists on graph, from startVertex to endVertex;
// otherwise returns false. Uses depth-first search algorithm.
{
UnboundedStackInterface stack = new LinkedStack();
UnboundedQueueInterface vertexQueue = new LinkedUnbndQueue();
boolean found = false;
String vertex;
String item;
graph.clearMarks();
stack.push(startVertex);
do
7. {
vertex = stack.top();
stack.pop();
if (vertex == endVertex)
found = true;
else
{
if (!graph.isMarked(vertex))
{
graph.markVertex(vertex);
vertexQueue = graph.getToVertices(vertex);
while (!vertexQueue.isEmpty())
{
item = vertexQueue.dequeue();
if (!graph.isMarked(item))
stack.push(item);
}
}
}
} while (!stack.isEmpty() && !found);
return found;
}
private static boolean isPath2(WeightedGraphInterface graph,
String startVertex,
String endVertex )
// Returns true if a path exists on graph, from startVertex to endVertex;
// otherwise returns false. Uses breadth-first search algorithm.
{
UnboundedQueueInterface queue = new LinkedUnbndQueue();
UnboundedQueueInterface vertexQueue = new LinkedUnbndQueue();
boolean found = false;
String vertex;
String item;
8. graph.clearMarks();
queue.enqueue(startVertex);
do
{
vertex = queue.dequeue();
if (vertex == endVertex)
found = true;
else
{
if (!graph.isMarked(vertex))
{
graph.markVertex(vertex);
vertexQueue = graph.getToVertices(vertex);
while (!vertexQueue.isEmpty())
{
item = vertexQueue.dequeue();
if (!graph.isMarked(item))
queue.enqueue(item);
}
}
}
} while (!queue.isEmpty() && !found);
return found;
}
public static void main(String[] args)
{
WeightedGraphInterface graph = new WeightedGraph();
String s0 = new String("Atlanta ");
String s1 = new String("Austin ");
String s2 = new String("Chicago ");
String s3 = new String("Dallas ");
String s4 = new String("Denver ");
String s5 = new String("Houston ");
12. result = isPath2(graph, s6, s1);
System.out.println("s6 s1 " + result);
System.out.println();
shortestPaths(graph, s6);
System.out.println();
System.out.println();
shortestPaths(graph, s4);
}
}
Solution
Given below is the completed code for WeightGraph class.
// Incomplete version
//----------------------------------------------------------------------------
// WeightedGraph.java by Dale/Joyce/Weems Chapter 9
//
// Implements a directed graph with weighted edges.
// Vertices are objects of class T and can be marked as having been visited.
// Edge weights are integers.
// Equivalence of vertices is determined by the vertices' equals method.
//
// General precondition: Except for the addVertex and hasVertex methods,
// any vertex passed as an argument to a method is in this graph.
//----------------------------------------------------------------------------
package ch09.graphs;
import ch05.queues.*;
public class WeightedGraph implements WeightedGraphInterface
{
public static final int NULL_EDGE = 0;
private static final int DEFCAP = 50; // default capacity
private int numVertices;
private int maxVertices;
private T[] vertices;
13. private int[][] edges;
private boolean[] marks; // marks[i] is mark for vertices[i]
public WeightedGraph()
// Instantiates a graph with capacity DEFCAP vertices.
{
numVertices = 0;
maxVertices = DEFCAP;
vertices = (T[]) new Object[DEFCAP];
marks = new boolean[DEFCAP];
edges = new int[DEFCAP][DEFCAP];
}
public WeightedGraph(int maxV)
// Instantiates a graph with capacity maxV.
{
numVertices = 0;
maxVertices = maxV;
vertices = (T[]) new Object[maxV];
marks = new boolean[maxV];
edges = new int[maxV][maxV];
}
public boolean isEmpty()
// Returns true if this graph is empty; otherwise, returns false.
{
return (numVertices == 0);
}
public boolean isFull()
// Returns true if this graph is full; otherwise, returns false.
{
return (numVertices == maxVertices);
}
public void addVertex(T vertex)
// Preconditions: This graph is not full.
// Vertex is not already in this graph.
// Vertex is not null.
//
// Adds vertex to this graph.
14. {
vertices[numVertices] = vertex;
for (int index = 0; index < numVertices; index++)
{
edges[numVertices][index] = NULL_EDGE;
edges[index][numVertices] = NULL_EDGE;
}
numVertices++;
}
public boolean hasVertex(T vertex)
// Returns true if this graph contains vertex; otherwise, returns false.
{
for(int i = 0; i < numVertices; i++)
{
if(vertices[i].equals(vertex))
return true;
}
return false;
}
private int indexIs(T vertex)
// Returns the index of vertex in vertices.
{
int index = 0;
while (!vertex.equals(vertices[index]))
index++;
return index;
}
public void addEdge(T fromVertex, T toVertex, int weight)
// Adds an edge with the specified weight from fromVertex to toVertex.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
edges[row][column] = weight;
15. }
public int weightIs(T fromVertex, T toVertex)
// If edge from fromVertex to toVertex exists, returns the weight of edge;
// otherwise, returns a special “null-edge” value.
{
int row;
int column;
row = indexIs(fromVertex);
column = indexIs(toVertex);
return edges[row][column];
}
public UnboundedQueueInterface getToVertices(T vertex)
// Returns a queue of the vertices that are adjacent from vertex.
{
UnboundedQueueInterface adjVertices = new LinkedUnbndQueue();
int fromIndex;
int toIndex;
fromIndex = indexIs(vertex);
for (toIndex = 0; toIndex < numVertices; toIndex++)
if (edges[fromIndex][toIndex] != NULL_EDGE)
adjVertices.enqueue(vertices[toIndex]);
return adjVertices;
}
public void clearMarks()
// Sets marks for all vertices to false.
{
for(int i = 0; i < numVertices; i++)
marks[i] = false;
}
public void markVertex(T vertex)
// Sets mark for vertex to true.
{
int idx = indexIs(vertex);
marks[idx] = true;
}
public boolean isMarked(T vertex)
16. // Returns true if vertex is marked; otherwise, returns false.
{
int idx = indexIs(vertex);
return marks[idx];
}
public T getUnmarked()
// Returns an unmarked vertex if any exist; otherwise, returns null.
{
for(int i = 0; i < numVertices; i++)
if(marks[i] == false)
return vertices[i];
return null;
}
}