Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
----------------------------------------------------------------------------------------------------------------- /* Graph class implemented with adjacency matrix: 1-D array for vertices, 2-D array to store edge information. Displays contents of both tables traversal depth-first with a Stack
breadth-first using a Queue
searches for a path by depth-first algorithm, together with distance
Graph is directed & uses the 7 town names below
Introducing Data Structures with Java
David Cousins 2010
*/
public class Graph {
static String[] Vertex = new String[7];
static boolean[] visited = new boolean[7];
static int[][] Edge = new int[7][7];
static DLNode head = new DLNode(0);
static DLNode end = new DLNode(0);
Graph() {
// set Vertex identifiers
Vertex[0] = "Sleepytown";
Vertex[1] = "Much Snoring";
Vertex[2] = "Great Snoring";
Vertex[3] = "Little Snoring";
Vertex[4] = "Lesser Snoring";
Vertex[5] = "Snoring on Sea";
Vertex[6] = "Snoring on the Hill";
for (int i = 0; i < 7; i++)
visited[i] = false;
// initialise edges to blank
for (int i = 0; i < 7; i++)
for (int j = 0; j < 7; j++)
Edge[i][j] = 0;
// set edge value weightings in the table
Edge[0][1] = 50; // Sleepytown to Much Snoring
Edge[1][0] = 50; // Much Snoring to Sleepytown
Edge[1][2] = 150; // Much Snoring to Great Snoring
Edge[2][1] = 150; // Great Snoring to Much Snoring
Edge[3][1] = 80; // Little Snoring to Much Snoring
Edge[2][3] = 180; // Great Snoring to Little Snoring
Edge[2][6] = 150; // Great Snoring to Snoring on the Hill
Edge[2][5] = 200; // Great Snoring to Snoring by Sea
Edge[5][2] = 200; // Snoring on Sea to Great Snoring
Edge[6][4] = 50; // Snoring on the Hill to Lesser Snoring
Edge[4][2] = 180; // Lesser Snoring to Great Snoring
}
// display format utility
public void formatLine(String item){
int spaces = 25 - item.length();
for (int i = 0; i<spaces; i++)
System.out.print(" ");;
}
// displays all graph data