Untitled

 avatar
unknown
java
2 years ago
2.8 kB
2
Indexable
package weblab;

import java.util.*;

class Edge {

  int from, to, weight;

  public Edge(int from, int to, int weight) {
    this.from = from;
    this.to = to;
    this.weight = weight;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o)
      return true;
    if (o == null || getClass() != o.getClass())
      return false;
    Edge edge = (Edge) o;
    return from == edge.from && to == edge.to && weight == edge.weight;
  }

  @Override
  public int hashCode() {
    return Objects.hash(from, to, weight);
  }
}

class Tuple implements Comparable<Tuple> {
    int id;

    int cost;

    Tuple(int id, int cost) {
      this.id = id;
      this.cost = cost;
    }

    @Override
    public int compareTo(Tuple o) {
      int res = Integer.signum(this.cost - o.cost);
      if (res == 0) {
        return Integer.signum(this.id - o.id);
      }
      return res;
    }
  }

class Solution {

  /**
   * @param n the number of nodes
   * @param m the number of edges
   * @param s the starting vertex (1 <= s <= n)
   * @param t the ending vertex (1 <= t <= n)
   * @param edges the set of edges of the graph, with endpoints labelled between 1 and n inclusive.
   * @return the time required to get out, or -1 if it is not possible to get out.
   */
  public static int getMeOuttaHere(int n, int m, int s, int t, Set<Edge> edges) {
    ArrayList<HashMap<Integer, Tuple>> arrayList = new ArrayList<>();
    for(int i = 0; i <= n; i++) {
        arrayList.add(i, new HashMap<>());
    }

    for (Edge edge : edges) {
        int edgeFrom = edge.from;
        int vertex = edge.to;
        int edgeWeight = edge.weight;
        arrayList.get(edgeFrom).put(vertex, new Tuple(vertex,edgeWeight));
    }

    PriorityQueue<Tuple> queue = new PriorityQueue<>();
    queue.add(new Tuple(s, 0)); 

    int[] key = new int[arrayList.size()];

    for (int i = 0; i < key.length; i++) {
        key[i] = Integer.MAX_VALUE;
    }
    
    key[s] = 0;

    boolean[] visited = new boolean[arrayList.size()];
        
    while (!queue.isEmpty()) {
      Tuple node = queue.remove();

      if (node.id == t) {
          return key[node.id];
      }
      
      HashMap<Integer,Tuple> currEntry = arrayList.get(node.id);

      if (visited[node.id] == false) {
        visited[node.id] = true;
        for (Map.Entry<Integer, Tuple> neighbour : currEntry.entrySet()) {
          int to = neighbour.getKey();
          int weight = neighbour.getValue().cost + key[node.id] + currEntry.size();
            System.out.println(to); 
          if(visited[to] == false && (weight < key[to])) {
            key[to] = weight; 
            queue.add(new Tuple(to, key[to])); 
          }
        }
      }
    }
    return visited[t] ? key[t] : -1;
  }
}
Editor is loading...