Skip to content
Snippets Groups Projects
Commit 2d13863d authored by Martin Vatshelle's avatar Martin Vatshelle
Browse files

after lecture

parent 7c6c7e3c
Branches master
No related tags found
No related merge requests found
......@@ -12,28 +12,26 @@ import java.util.Stack;
*/
public class ShortestPath {
public static <V> HashMap<V,Integer> search(WeightedGraph<V, Integer> graph, V start) {
HashMap<V,Integer> distances = new HashMap<>();
PriorityQueue<Pair<V>> toSearch = new PriorityQueue<>();
public static <V> HashMap<V,Integer> search(WeightedGraph<V, Integer> graph, V start) { //O(n + m log m )
HashMap<V,Integer> distances = new HashMap<>(); //O(1)
PriorityQueue<Pair<V>> toSearch = new PriorityQueue<>();//O(1)
//add start node
toSearch.add(new Pair<V>(start, 0));
toSearch.add(new Pair<V>(start, 0)); //O(1)
while(!toSearch.isEmpty()) {
Pair<V> best = toSearch.remove();
while(!toSearch.isEmpty()) { //O(m) times
Pair<V> best = toSearch.remove(); //m times O(log m)
if(distances.containsKey(best.getVetrex()))
if(distances.containsKey(best.getVertex())) //O(1)*m = O(m)
continue;
else {
distances.put(best.getVetrex(), best.getDistance());
for(V neighbour : graph.neighbours(best.getVetrex())) {
int weight = best.getDistance()+graph.getWeight(best.getVetrex(),neighbour);
toSearch.add(new Pair<V>(neighbour, weight));
else { //n times O(n + m*log m)
distances.put(best.getVertex(), best.getDistance()); //O(1)
for(V neighbour : graph.neighbours(best.getVertex())) { //2m times sum av gradtall til hver node er 2m
int weight = best.getDistance()+graph.getWeight(best.getVertex(),neighbour); //O(1)
toSearch.add(new Pair<V>(neighbour, weight)); //O(log m)
}
}
}
}
return distances;
}
}
......@@ -47,7 +45,7 @@ class Pair<V> implements Comparable<Pair<V>>{
this.distance = distance;
}
V getVetrex() {
V getVertex() {
return vertex;
}
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment