Source of FlightsGraphDemo.java


  1: //FlightsGraphDemo.java

  3: import java.util.List;

  5: public class FlightsGraphDemo
  6: {
  7:     public static void main(String[] args)
  8:     {
  9:         // Create a new Graph object
 10:         Graph graph1 = new Graph();

 12:         // Add vertices and edges representing plane flights
 13:         Vertex vertexA = graph1.addVertex("Tokyo");
 14:         Vertex vertexB = graph1.addVertex("New York");
 15:         Vertex vertexC = graph1.addVertex("London");
 16:         Vertex vertexD = graph1.addVertex("Sydney");
 17:         graph1.addUndirectedEdge(vertexA, vertexB, 6743);
 18:         graph1.addUndirectedEdge(vertexA, vertexC, 5941);
 19:         graph1.addUndirectedEdge(vertexA, vertexD, 4863);
 20:         graph1.addUndirectedEdge(vertexB, vertexC, 3425);
 21:         graph1.addUndirectedEdge(vertexB, vertexD, 9868);
 22:         graph1.addUndirectedEdge(vertexC, vertexD, 10562);

 24:         // Show the graph's vertices and edges
 25:         for (Vertex vertex : graph1.getVertices())
 26:         {
 27:             System.out.println("Location: " + vertex.label);

 29:             // Show outgoing edges (flights from location)
 30:             System.out.printf("  Flights from %s:%n", vertex.label);
 31:             for (Edge outgoingEdge : graph1.getEdgesFrom(vertex))
 32:             {
 33:                 System.out.printf
 34:                 (
 35:                     "   - %s to %s, %d miles%n",
 36:                     vertex.label,
 37:                     outgoingEdge.toVertex.label,
 38:                     (int)outgoingEdge.weight
 39:                 );
 40:             }

 42:             // Show incoming edges (flights to location)
 43:             System.out.printf("  Flights to %s:%n", vertex.label);
 44:             for (Edge incomingEdge : graph1.getEdgesTo(vertex))
 45:             {
 46:                 System.out.printf
 47:                 (
 48:                     "   - %s to %s, %d miles%n",
 49:                     incomingEdge.fromVertex.label,
 50:                     vertex.label,
 51:                     (int)incomingEdge.weight
 52:                 );
 53:             }
 54:         }
 55:     }
 56: }