Java Reference
In-Depth Information
35 java.util.ArrayList<AbstractGraph.Edge> edgeList
36 = new java.util.ArrayList<>();
37 edgeList.add( new AbstractGraph.Edge( 0 , 2 ));
38 edgeList.add( new AbstractGraph.Edge( 1 , 2 ));
39 edgeList.add( new AbstractGraph.Edge( 2 , 4 ));
40 edgeList.add( new AbstractGraph.Edge( 3 , 4 ));
41 // Create a graph with 5 vertices
42 Graph<String> graph2 = new UnweightedGraph<>
43 (java.util.Arrays.asList(names), edgeList);
44 System.out.println( "\nThe number of vertices in graph2: "
45 + graph2.getSize());
46 System.out.println( "The edges for graph2:" );
47 graph2.printEdges();
48 }
49 }
list of Edge objects
create a graph
print edges
The number of vertices in graph1: 12
The vertex with index 1 is San Francisco
The index for Miami is 9
The edges for graph1:
Seattle (0): (0, 1) (0, 3) (0, 5)
San Francisco (1): (1, 0) (1, 2) (1, 3)
Los Angeles (2): (2, 1) (2, 3) (2, 4) (2, 10)
Denver (3): (3, 0) (3, 1) (3, 2) (3, 4) (3, 5)
Kansas City (4): (4, 2) (4, 3) (4, 5) (4, 7) (4, 8) (4, 10)
Chicago (5): (5, 0) (5, 3) (5, 4) (5, 6) (5, 7)
Boston (6): (6, 5) (6, 7)
New York (7): (7, 4) (7, 5) (7, 6) (7, 8)
Atlanta (8): (8, 4) (8, 7) (8, 9) (8, 10) (8, 11)
Miami (9): (9, 8) (9, 11)
Dallas (10): (10, 2) (10, 4) (10, 8) (10, 11)
Houston (11): (11, 8) (11, 9) (11, 10)
The number of vertices in graph2: 5
The edges for graph2:
Peter (0): (0, 2)
Jane (1): (1, 2)
Mark (2): (2, 4)
Cindy (3): (3, 4)
Wendy (4):
The program creates graph1 for the graph in FigureĀ 28.1 in lines 3-23. The vertices for graph1
are defined in lines 3-5. The edges for graph1 are defined in 8-21. The edges are represented
using a two-dimensional array. For each row i in the array, edges[i][0] and edges[i][1]
indicate that there is an edge from vertex edges[i][0] to vertex edges[i][1] . For exam-
ple, the first row, { 0 , 1 }, represents the edge from vertex 0 ( edges[0][0] ) to vertex 1
( edges[0][1] ). The row { 0 , 5 } represents the edge from vertex 0 ( edges[2][0] ) to ver-
tex 5 ( edges[2][1] ). The graph is created in line 23. Line 31 invokes the printEdges()
method on graph1 to display all edges in graph1 .
The program creates graph2 for the graph in FigureĀ 28.3a in lines 34-43. The edges
for graph2 are defined in lines 37-40. graph2 is created using a list of Edge objects in
line 43. Line 47 invokes the printEdges() method on graph2 to display all edges in
graph2 .
Note that both graph1 and graph2 contain the vertices of strings. The vertices are asso-
ciated with indices 0 , 1 , . . . , n-1 . The index is the location of the vertex in vertices . For
example, the index of vertex Miami is 9 .
 
Search WWH ::




Custom Search