SlideShare a Scribd company logo
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.
{
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.
{
}
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.*;
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))
{
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
{
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;
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 ");
String s6 = new String("Washington");
graph.addVertex(s0);
graph.addVertex(s1);
graph.addVertex(s2);
graph.addVertex(s3);
graph.addVertex(s4);
graph.addVertex(s5);
graph.addVertex(s6);
graph.addEdge(s0, s5, 800);
graph.addEdge(s0, s6, 600);
graph.addEdge(s1, s3, 200);
graph.addEdge(s1, s5, 160);
graph.addEdge(s2, s4, 1000);
graph.addEdge(s3, s1, 200);
graph.addEdge(s3, s2, 900);
graph.addEdge(s3, s4, 780);
graph.addEdge(s4, s0, 1400);
graph.addEdge(s4, s2, 1000);
graph.addEdge(s5, s0, 800);
graph.addEdge(s6, s0, 600);
graph.addEdge(s6, s3, 1300);
boolean result;
System.out.println("depth first ...");
result = isPath(graph, s1, s2);
System.out.println("s1 s2 " + result);
result = isPath(graph, s1, s6);
System.out.println("s1 s6 " + result);
result = isPath(graph, s6, s5);
System.out.println("s6 s5 " + result);
result = isPath(graph, s6, s3);
System.out.println("s6 s3 " + result);
result = isPath(graph, s6, s1);
System.out.println("s6 s1 " + result);
System.out.println();
System.out.println("breadth first ...");
result = isPath2(graph, s1, s2);
System.out.println("s1 s2 " + result);
result = isPath2(graph, s1, s6);
System.out.println("s1 s6 " + result);
result = isPath2(graph, s6, s5);
System.out.println("s6 s5 " + result);
result = isPath2(graph, s6, s3);
System.out.println("s6 s3 " + result);
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);
System.out.println();
System.out.println();
System.out.println("a new graph without Wash - Dallas leg");
System.out.println();
graph = new WeightedGraph();
s0 = new String("Atlanta ");
s1 = new String("Austin ");
s2 = new String("Chicago ");
s3 = new String("Dallas ");
s4 = new String("Denver ");
s5 = new String("Houston ");
s6 = new String("Washington");
graph.addVertex(s0);
graph.addVertex(s1);
graph.addVertex(s2);
graph.addVertex(s3);
graph.addVertex(s4);
graph.addVertex(s5);
graph.addVertex(s6);
graph.addEdge(s0, s5, 800);
graph.addEdge(s0, s6, 600);
graph.addEdge(s1, s3, 200);
graph.addEdge(s1, s5, 160);
graph.addEdge(s2, s4, 1000);
graph.addEdge(s3, s1, 200);
graph.addEdge(s3, s2, 900);
graph.addEdge(s3, s4, 780);
graph.addEdge(s4, s0, 1400);
graph.addEdge(s4, s2, 1000);
graph.addEdge(s5, s0, 800);
graph.addEdge(s6, s0, 600);
// graph.addEdge(s6, s3, 1300);
System.out.println("depth first ...");
result = isPath(graph, s1, s2);
System.out.println("s1 s2 " + result);
result = isPath(graph, s1, s6);
System.out.println("s1 s6 " + result);
result = isPath(graph, s6, s5);
System.out.println("s6 s5 " + result);
result = isPath(graph, s6, s3);
System.out.println("s6 s3 " + result);
result = isPath(graph, s6, s1);
System.out.println("s6 s1 " + result);
System.out.println();
System.out.println("breadth first ...");
result = isPath2(graph, s1, s2);
System.out.println("s1 s2 " + result);
result = isPath2(graph, s1, s6);
System.out.println("s1 s6 " + result);
result = isPath2(graph, s6, s5);
System.out.println("s6 s5 " + result);
result = isPath2(graph, s6, s3);
System.out.println("s6 s3 " + result);
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;
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.
{
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;
}
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)
// 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;
}
}

More Related Content

PDF
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
PDF
Im having trouble figuring out how to code these sections for an a.pdf
PDF
Please finish the codes in Graph.h class.#################### Vert.pdf
KEY
openFrameworks 007 - 3D
DOCX
Write a program that reads a graph from a file and determines whether.docx
PDF
Internal workshop es6_2015
PDF
I have compilation errors that I'm struggling with in my code- please.pdf
DOCX
Write a program that reads a connected graph from a file and displays.docx
ImplementDijkstra’s algorithm using the graph class you implemente.pdf
Im having trouble figuring out how to code these sections for an a.pdf
Please finish the codes in Graph.h class.#################### Vert.pdf
openFrameworks 007 - 3D
Write a program that reads a graph from a file and determines whether.docx
Internal workshop es6_2015
I have compilation errors that I'm struggling with in my code- please.pdf
Write a program that reads a connected graph from a file and displays.docx

Similar to Complete the implementation of the Weighted Graph that we began in t.pdf (14)

PDF
Write CC++ a program that inputs a weighted undirected graph and fi.pdf
PDF
Im looking for coding help I dont really need this to be explained.pdf
PPTX
Implementation of graphs, adjaceny matrix
PDF
Computer Graphics in Java and Scala - Part 1b
PDF
SpreadsheetWriter.javaCan you please help me the JAVA program Let.pdf
PDF
05 Geographic scripting in uDig - halfway between user and developer
DOCX
This code currently works. Run it and get a screen shot of its ou.docx
PDF
AJUG April 2011 Cascading example
PPTX
Arrays
PDF
Create a java project that - Draw a circle with three random init.pdf
PPT
Unit26 shortest pathalgorithm
PDF
complete the following functions in c++ singleRotation putNo.pdf
PPTX
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
PDF
Please implement in Java. comments would be appreciated 5.pdf
Write CC++ a program that inputs a weighted undirected graph and fi.pdf
Im looking for coding help I dont really need this to be explained.pdf
Implementation of graphs, adjaceny matrix
Computer Graphics in Java and Scala - Part 1b
SpreadsheetWriter.javaCan you please help me the JAVA program Let.pdf
05 Geographic scripting in uDig - halfway between user and developer
This code currently works. Run it and get a screen shot of its ou.docx
AJUG April 2011 Cascading example
Arrays
Create a java project that - Draw a circle with three random init.pdf
Unit26 shortest pathalgorithm
complete the following functions in c++ singleRotation putNo.pdf
ABSTRACT GRAPH MACHINE: MODELING ORDERINGS IN ASYNCHRONOUS DISTRIBUTED-MEMORY...
Please implement in Java. comments would be appreciated 5.pdf
Ad

More from marketing413921 (20)

PDF
Can someone help me please I need help writing this code using Java.pdf
PDF
C++ in XcodePass the values by reference to complete the programmi.pdf
PDF
Assume an infix expression can only contain five operators, + .pdf
PDF
appropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdf
PDF
Arrange the following event in chronological order. The Roman Republi.pdf
PDF
Why do we need internal control in an organization What is its purp.pdf
PDF
Why Diamond and semiconductor material like Silicon are used in elect.pdf
PDF
Which of the following was NOT a goal of Titchener’s psychologyA..pdf
PDF
You discover a new kind of fungus with large, square-shaped spores. .pdf
PDF
Write 1-2 pages of the definitions of the followings (Use APA forma.pdf
PDF
Which cell type does not move materials Which of the following cell .pdf
PDF
What is the practical relevanceirrelevance of different digital med.pdf
PDF
using MATLABplease write down the code to compute these functions.pdf
PDF
What are the main duties of the Canadian Engineering Accreditation B.pdf
PDF
A supererogatory action is one in which a person must engage. T or F.pdf
PDF
The purpose of specialized lacunae are to provide structure to th.pdf
PDF
The following code is an implementation of the producer consumer pro.pdf
PDF
Prerequisites — Classes or Knowledge Required for this Course.pdf
PDF
Please dont answer if you cannot complete all the requirements. Th.pdf
PDF
Part 1 Select a controversial current topic and describe the litera.pdf
Can someone help me please I need help writing this code using Java.pdf
C++ in XcodePass the values by reference to complete the programmi.pdf
Assume an infix expression can only contain five operators, + .pdf
appropriate nursing interventionsmanagement -COPD -Crackles, wheezi.pdf
Arrange the following event in chronological order. The Roman Republi.pdf
Why do we need internal control in an organization What is its purp.pdf
Why Diamond and semiconductor material like Silicon are used in elect.pdf
Which of the following was NOT a goal of Titchener’s psychologyA..pdf
You discover a new kind of fungus with large, square-shaped spores. .pdf
Write 1-2 pages of the definitions of the followings (Use APA forma.pdf
Which cell type does not move materials Which of the following cell .pdf
What is the practical relevanceirrelevance of different digital med.pdf
using MATLABplease write down the code to compute these functions.pdf
What are the main duties of the Canadian Engineering Accreditation B.pdf
A supererogatory action is one in which a person must engage. T or F.pdf
The purpose of specialized lacunae are to provide structure to th.pdf
The following code is an implementation of the producer consumer pro.pdf
Prerequisites — Classes or Knowledge Required for this Course.pdf
Please dont answer if you cannot complete all the requirements. Th.pdf
Part 1 Select a controversial current topic and describe the litera.pdf
Ad

Recently uploaded (20)

PPTX
human mycosis Human fungal infections are called human mycosis..pptx
PPTX
202450812 BayCHI UCSC-SV 20250812 v17.pptx
PDF
Complications of Minimal Access Surgery at WLH
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PPTX
GDM (1) (1).pptx small presentation for students
PDF
RMMM.pdf make it easy to upload and study
PPTX
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PPTX
Cell Structure & Organelles in detailed.
PDF
Computing-Curriculum for Schools in Ghana
PPTX
Cell Types and Its function , kingdom of life
PDF
Classroom Observation Tools for Teachers
PDF
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
01-Introduction-to-Information-Management.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
human mycosis Human fungal infections are called human mycosis..pptx
202450812 BayCHI UCSC-SV 20250812 v17.pptx
Complications of Minimal Access Surgery at WLH
Pharmacology of Heart Failure /Pharmacotherapy of CHF
GDM (1) (1).pptx small presentation for students
RMMM.pdf make it easy to upload and study
Introduction-to-Literarature-and-Literary-Studies-week-Prelim-coverage.pptx
O5-L3 Freight Transport Ops (International) V1.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Supply Chain Operations Speaking Notes -ICLT Program
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Cell Structure & Organelles in detailed.
Computing-Curriculum for Schools in Ghana
Cell Types and Its function , kingdom of life
Classroom Observation Tools for Teachers
ANTIBIOTICS.pptx.pdf………………… xxxxxxxxxxxxx
STATICS OF THE RIGID BODIES Hibbelers.pdf
01-Introduction-to-Information-Management.pdf
Anesthesia in Laparoscopic Surgery in India
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf

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 ");
  • 9. String s6 = new String("Washington"); graph.addVertex(s0); graph.addVertex(s1); graph.addVertex(s2); graph.addVertex(s3); graph.addVertex(s4); graph.addVertex(s5); graph.addVertex(s6); graph.addEdge(s0, s5, 800); graph.addEdge(s0, s6, 600); graph.addEdge(s1, s3, 200); graph.addEdge(s1, s5, 160); graph.addEdge(s2, s4, 1000); graph.addEdge(s3, s1, 200); graph.addEdge(s3, s2, 900); graph.addEdge(s3, s4, 780); graph.addEdge(s4, s0, 1400); graph.addEdge(s4, s2, 1000); graph.addEdge(s5, s0, 800); graph.addEdge(s6, s0, 600); graph.addEdge(s6, s3, 1300); boolean result; System.out.println("depth first ..."); result = isPath(graph, s1, s2); System.out.println("s1 s2 " + result); result = isPath(graph, s1, s6); System.out.println("s1 s6 " + result); result = isPath(graph, s6, s5); System.out.println("s6 s5 " + result); result = isPath(graph, s6, s3); System.out.println("s6 s3 " + result); result = isPath(graph, s6, s1); System.out.println("s6 s1 " + result); System.out.println(); System.out.println("breadth first ...");
  • 10. result = isPath2(graph, s1, s2); System.out.println("s1 s2 " + result); result = isPath2(graph, s1, s6); System.out.println("s1 s6 " + result); result = isPath2(graph, s6, s5); System.out.println("s6 s5 " + result); result = isPath2(graph, s6, s3); System.out.println("s6 s3 " + result); 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); System.out.println(); System.out.println(); System.out.println("a new graph without Wash - Dallas leg"); System.out.println(); graph = new WeightedGraph(); s0 = new String("Atlanta "); s1 = new String("Austin "); s2 = new String("Chicago "); s3 = new String("Dallas "); s4 = new String("Denver "); s5 = new String("Houston "); s6 = new String("Washington"); graph.addVertex(s0); graph.addVertex(s1); graph.addVertex(s2); graph.addVertex(s3); graph.addVertex(s4); graph.addVertex(s5);
  • 11. graph.addVertex(s6); graph.addEdge(s0, s5, 800); graph.addEdge(s0, s6, 600); graph.addEdge(s1, s3, 200); graph.addEdge(s1, s5, 160); graph.addEdge(s2, s4, 1000); graph.addEdge(s3, s1, 200); graph.addEdge(s3, s2, 900); graph.addEdge(s3, s4, 780); graph.addEdge(s4, s0, 1400); graph.addEdge(s4, s2, 1000); graph.addEdge(s5, s0, 800); graph.addEdge(s6, s0, 600); // graph.addEdge(s6, s3, 1300); System.out.println("depth first ..."); result = isPath(graph, s1, s2); System.out.println("s1 s2 " + result); result = isPath(graph, s1, s6); System.out.println("s1 s6 " + result); result = isPath(graph, s6, s5); System.out.println("s6 s5 " + result); result = isPath(graph, s6, s3); System.out.println("s6 s3 " + result); result = isPath(graph, s6, s1); System.out.println("s6 s1 " + result); System.out.println(); System.out.println("breadth first ..."); result = isPath2(graph, s1, s2); System.out.println("s1 s2 " + result); result = isPath2(graph, s1, s6); System.out.println("s1 s6 " + result); result = isPath2(graph, s6, s5); System.out.println("s6 s5 " + result); result = isPath2(graph, s6, s3); System.out.println("s6 s3 " + result);
  • 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; } }