Java Reference
In-Depth Information
255
return searchOrder.size();
256 }
257
258 /** Return the path of vertices from a vertex to the root */
259 public List<V> getPath( int index) {
260 ArrayList<V> path = new ArrayList<>();
261
262 do {
263 path.add(vertices.get(index));
264 index = parent[index];
265 }
266
while (index != -1 );
267
268
return path;
269 }
270
271 /** Print a path from the root to vertex v */
272 public void printPath( int index) {
273 List<V> path = getPath(index);
274 System.out.print( "A path from " + vertices.get(root) + " to " +
275 vertices.get(index) + ": " );
276 for ( int i = path.size() - 1 ; i >= 0 ; i--)
277 System.out.print(path.get(i) + " " );
278 }
279
280 /** Print the whole tree */
281 public void printTree() {
282 System.out.println( "Root is: " + vertices.get(root));
283 System.out.print( "Edges: " );
284 for ( int i = 0 ; i < parent.length; i++) {
285 if (parent[i] != -1 ) {
286 // Display an edge
287 System.out.print( "(" + vertices.get(parent[i]) + ", " +
288 vertices.get(i) + ") " );
289 }
290 }
291 System.out.println();
292 }
293 }
294 }
L ISTING 28.4
UnweightedGraph.java
1 import java.util.*;
2
3 public class UnweightedGraph<V> extends AbstractGraph<V> {
4 /** Construct an empty graph */
5 public UnweightedGraph() {
6 }
7
8
no-arg constructor
/** Construct a graph from vertices and edges stored in arrays */
9
public UnweightedGraph(V[] vertices, int [][] edges) {
constructor
10
super (vertices, edges);
11 }
12
13
/** Construct a graph from vertices and edges stored in List */
14
public UnweightedGraph(List<V> vertices, List<Edge> edges) {
constructor
15
super (vertices, edges);
16 }
17
18
/** Construct a graph for integer vertices 0, 1, 2 and edge list */
 
 
Search WWH ::




Custom Search