Exemplo n.º 1
0
  private static Map<Integer, List<Edge>> buildGraph(List<Edge> edges) {

    Map<Integer, List<Edge>> graph = new TreeMap<>();
    for (Edge edge : edges) {
      if (!graph.containsKey(edge.getStartNode())) {
        graph.put((Integer) edge.getStartNode(), new ArrayList<Edge>());
      }
      graph.get(edge.getStartNode()).add(edge);
      if (!graph.containsKey(edge.getEndNode())) {
        graph.put((Integer) edge.getEndNode(), new ArrayList<Edge>());
      }
      Edge reversedEdge = new Edge(edge.getEndNode(), edge.getStartNode(), edge.getWightl());
      graph.get(edge.getEndNode()).add(reversedEdge);
    }

    return graph;
  }
Exemplo n.º 2
0
  public Set<NodeEdgePair> getAdjecents() {
    // Set<Edge> edges = getEdges();
    Set<NodeEdgePair> nodes = new HashSet<>();

    for (Edge e : edges) {
      Node start = e.getStartNode();
      Node end = e.getEndNode();
      Node other = start == this ? end : start;
      nodes.add(new NodeEdgePair(e, other));
    }
    return nodes;
  }
Exemplo n.º 3
0
  // Dosn't work like dijkstra. Work like kruskal
  private static void dijkstra(List<Edge> edges, int startingNode) {

    Map<Integer, List<Edge>> graph = buildGraph(edges);
    // use reverse order priority queue
    PriorityQueue<Edge> priorityQueue = new PriorityQueue<Edge>();

    boolean[] visitedNode = new boolean[graph.size()];
    int[] parent = new int[graph.size()];
    int[] distance = new int[graph.size()];
    // initialize the parent and distance array
    for (int i = 0; i < distance.length; i++) {
      distance[i] = Integer.MAX_VALUE;
      parent[i] = -1;
    }
    visitedNode[startingNode] = true;
    parent[startingNode] = startingNode;
    distance[startingNode] = 0;

    do {
      // TODO
      List<Edge> childOfStartingtNode = graph.get(startingNode);
      for (Edge edge : childOfStartingtNode) {
        if (!edge.isConnected()) {

          priorityQueue.add(edge);
        }
      }

      Edge currentEdge = priorityQueue.poll();
      currentEdge.setConnected(true);
      if (!visitedNode[currentEdge.getEndNode()]) {
        visitedNode[currentEdge.getEndNode()] = true;
        parent[currentEdge.getEndNode()] = currentEdge.getStartNode();

        int newDistance = distance[currentEdge.getStartNode()] + currentEdge.getWightl();

        if (distance[currentEdge.getEndNode()] > newDistance) {
          distance[currentEdge.getEndNode()] = newDistance;
        }
        startingNode = currentEdge.getEndNode();
      }

    } while (priorityQueue.size() > 0);

    for (int i = 0; i < graph.size(); i++) {
      System.out.println("Node: " + i);
      System.out.println("distance: " + distance[i]);
      System.out.println("Parent: " + parent[i]);
      System.out.println();
    }
  }