You are viewing a single comment's thread. Return to all comments →
Java Dijkstra's Algorithm O((gEdges+gNodes)loggNodes)
class Edge { int to, weight; public Edge(int to, int weight) { this.to = to; this.weight = weight; } } class Node implements Comparable<Node> { int id; long cost; public Node(int id, long cost) { this.id = id; this.cost = cost; } @Override public int compareTo(Node other) { return Long.compare(this.cost, other.cost); } } class Result { public static void getCost(int gNodes, List<Integer> gFrom, List<Integer> gTo, List<Integer> gWeight) { List<List<Edge>> graph = new ArrayList<>(gNodes + 1); for (int i = 0; i <= gNodes; i++) { graph.add(new ArrayList<>()); } for (int i = 0; i < gFrom.size(); i++) { int from = gFrom.get(i); int to = gTo.get(i); int weight = gWeight.get(i); graph.get(from).add(new Edge(to, weight)); graph.get(to).add(new Edge(from, weight)); } long[] dist = new long[gNodes + 1]; Arrays.fill(dist, Long.MAX_VALUE); dist[1] = 0; PriorityQueue<Node> pq = new PriorityQueue<>(); pq.add(new Node(1, 0)); while (!pq.isEmpty()) { Node current = pq.poll(); int u = current.id; long currentCost = current.cost; if (currentCost > dist[u]) continue; for (Edge edge : graph.get(u)) { int v = edge.to; long newCost = edge.weight; if (currentCost < newCost) { newCost -= currentCost; } else { newCost = 0; } if (dist[u] + newCost < dist[v]) { dist[v] = dist[u] + newCost; pq.add(new Node(v, dist[v])); } } } long result = dist[gNodes]; if (result == Long.MAX_VALUE) { System.out.println("NO PATH EXISTS"); } else { System.out.println(result); } } }
Seems like cookies are disabled on this browser, please enable them to open this website
Jack goes to Rapture
You are viewing a single comment's thread. Return to all comments →
Java Dijkstra's Algorithm O((gEdges+gNodes)loggNodes)