Example #1
0
  public static void main(String[] args) {
    Graph graph = new Graph(8);
    for (int i = 0; i < 8; i++) graph.addVertex((char) ('A' + i));

    graph.addEdge(0, 1); // A-B
    graph.addEdge(1, 2); // B-C
    graph.addEdge(1, 7); // B-H
    graph.addEdge(2, 3); // C-D
    graph.addEdge(2, 4); // C-E
    graph.addEdge(7, 4); // H-E
    graph.addEdge(4, 5); // E-F
    graph.addEdge(4, 6); // E-G

    graph.dfs();
    System.out.println();
    graph.bfs();
    System.out.println();
    graph.dijkstra(0);
  }
Example #2
0
  public static void main(String[] args) {
    // TODO Auto-generated method stub

    Graph adjList;

    Graph graph = new Graph(4);
    graph.addEdge(1, 2);
    graph.addEdge(1, 3);
    graph.addEdge(2, 3);
    graph.addEdge(3, 1);
    graph.addEdge(3, 4);
    graph.addEdge(4, 4);

    System.out.println("Following is Breadth First Traversal (starting from vertex 2) \n");
    graph.bfs(1);

    boolean[] visited = new boolean[graph.nodes.size() + 1];

    System.out.println("\n Following is Depth First Traversal (starting from vertex 2) \n");
    for (int i = graph.nodes.size(); i > 0; i--) if (!visited[i]) graph.dfs(i, visited);
  }
Example #3
0
  public static void main(String[] args) {
    String[] vertices = {
      "Seattle",
      "San Francisco",
      "Los Angeles",
      "Denver",
      "Kansas City",
      "Chicago",
      "Boston",
      "New York",
      "Atlanta",
      "Miami",
      "Dallas",
      "Houston"
    };

    int[][] edges = {
      {0, 1}, {0, 3}, {0, 5}, {1, 0}, {1, 2}, {1, 3}, {2, 1}, {2, 3}, {2, 4}, {2, 10}, {3, 0},
      {3, 1}, {3, 2}, {3, 4}, {3, 5}, {4, 2}, {4, 3}, {4, 5}, {4, 7}, {4, 8}, {4, 10}, {5, 0},
      {5, 3}, {5, 4}, {5, 6}, {5, 7}, {6, 5}, {6, 7}, {7, 4}, {7, 5}, {7, 6}, {7, 8}, {8, 4},
      {8, 7}, {8, 9}, {8, 10}, {8, 11}, {9, 8}, {9, 11}, {10, 2}, {10, 4}, {10, 8}, {10, 11},
      {11, 8}, {11, 9}, {11, 10}
    };

    Graph<String> graph = new UnweightedGraph<String>(edges, vertices);
    AbstractGraph<String>.Tree dfs = graph.dfs(5); // 5 is Chicago

    java.util.List<Integer> searchOrders = dfs.getSearchOrders();
    System.out.println(
        dfs.getNumberOfVerticesFound() + " vertices are searched in this DFS order:");
    for (int i = 0; i < searchOrders.size(); i++)
      System.out.print(graph.getVertex(searchOrders.get(i)) + " ");
    System.out.println();

    for (int i = 0; i < searchOrders.size(); i++)
      if (dfs.getParent(i) != -1)
        System.out.println(
            "parent of " + graph.getVertex(i) + " is " + graph.getVertex(dfs.getParent(i)));
  }
Example #4
0
 public static void main(String[] args) {
   String[] dependencies = {"1 2 3", "0 4 5", "0 6", "0 5", "1", "1 3", "2"};
   Graph g = new Graph(dependencies);
   g.dfs("0");
   g.bfs("0");
 }
Example #5
0
 public void dfs(String vertex) {
   Set<String> visited = new TreeSet<String>();
   dfs(vertex, visited);
   System.out.println();
 }