예제 #1
0
  public static void main(String[] args) {
    String[] graphVertexes = new String[] {"A", "B", "C", "D", "E"};
    boolean[][] adjacencyMatrix = makeRandomAdjacencyMatrix(graphVertexes);
    printAdjacencyMatrix(graphVertexes, adjacencyMatrix);

    System.out.println(
        "Vertex Set with Connections based on the above connections matrix (-> = root)");
    GraphImpl<String> letterGraph = makeNewGraph(graphVertexes, 2, adjacencyMatrix);
    System.out.println(letterGraph);

    System.out.println("The Depth First Search (DFS) elements");
    Iterator<String> dfsIterator = letterGraph.depthFirstSearchIterator();
    while (dfsIterator.hasNext()) {
      String value = dfsIterator.next();
      if (dfsIterator.hasNext()) {
        System.out.print(value + " -> ");
      } else {
        System.out.print(value);
      }
    }

    System.out.println("");
    System.out.println("The Breadth First Search (BFS) elements");
    Iterator<String> bfsIterator = letterGraph.breadthFirstSearchIterator();
    while (bfsIterator.hasNext()) {
      String value = bfsIterator.next();
      if (bfsIterator.hasNext()) {
        System.out.print(value + " -> ");
      } else {
        System.out.print(value);
      }
    }
  }
예제 #2
0
  /**
   * of the vertex values.
   *
   * @param vertexValues is a set of vertex values.
   * @param rootIndex is the root index of the vertex values considered the root.
   * @param adjacencyMatrix is the adjacency matrix.
   * @return A new graph with the vertex values, a chosen root index of the list and an adjacency
   *     matrix of the connections.
   */
  public static GraphImpl<String> makeNewGraph(
      String[] vertexValues, int rootIndex, boolean[][] adjacencyMatrix) {
    Preconditions.checkArgument(vertexValues != null, "The vertex values must be provided.");
    Preconditions.checkArgument(rootIndex >= 0, "The root index must be greater or equals to 0.");
    Preconditions.checkArgument(adjacencyMatrix != null, "The adjacency matrix must be provided.");

    GraphImpl<String> newGraph = new GraphImpl<>();
    newGraph.rootIndex = rootIndex;
    newGraph.vertexes = new Vertex[vertexValues.length];
    for (int i = 0; i < adjacencyMatrix.length; i++) {
      List<String> connections = makeConnections(vertexValues, adjacencyMatrix, i);
      newGraph.vertexes[i] = new Vertex<>(vertexValues[i], connections);
    }
    return newGraph;
  }