Пример #1
0
 // Sets this graph to have the same structure as the input graph
 public ExpandableGraph(Graph g) {
   numVerts = g.numVertices();
   Map<Integer, Integer>[] other = g.getAdjList();
   adjList = new ArrayList<Map<Integer, Integer>>(numVerts);
   for (int i = 0; i < other.length; ++i) {
     HashMap<Integer, Integer> next = new HashMap<Integer, Integer>();
     for (int key : other[i].keySet()) {
       if (other[i].get(key) < 0) numNegEdges++;
       next.put(key, other[i].get(key));
     }
     adjList.add(next);
   }
 }
Пример #2
0
  public static void main(String[] args) {
    System.out.println("DFS");

    // create a graph and connect some vertices
    Graph g = new Graph(8);
    g.addEdge(1, 3);
    g.addEdge(3, 4);
    g.addEdge(4, 6);

    // create a dfs structure based on a subject vertex
    int subjV = 3;
    DFS dfs = new DFS(g, subjV);
    System.out.println("subject vertex: " + subjV);
    System.out.println("# of vertices visited: " + dfs.numVisited());

    // show the dfs structure based on the subject vertex
    for (int v = 0; v < g.numVertices(); v++) {
      if (dfs.visited(v)) {
        System.out.print(v + " ");
      }
    }
  }
Пример #3
0
  // returns a tour containing the shortest path TwoOpt finds
  public Tour findShortestPath(Graph g) {
    numVertices = g.numVertices();

    Tour start = g.getRandomTour();
    Tour comparison;

    int c = 1;
    while (c > 0) {
      c = 0;
      for (int i = 0; i < numVertices; i++) {
        for (int j = 0; j < i; j++) {
          comparison = new Tour(neighborVertexSet(start.verticesSoFar(), j, i), g);
          // System.out.printf("%s", comparison.toString());
          if (comparison.getLength() < start.getLength()) {
            start = comparison;
            c++;
          }
        }
      }
    }

    return start;
  }
Пример #4
0
 /**
  * CTOR: traverse the supplied graph starting from the subject vertex
  *
  * @param g the Graph instance to traverse
  * @param subjV the subject vertex to start from
  */
 public DFS(Graph g, int subjV) {
   mVisited = new boolean[g.numVertices()];
   traverse(g, subjV);
 }