# UCS and Dijkstra's algorithm do both of them give the minimal cost between two vertices?

i tried both algorithm to find the shortest path with minimal cost between two vertices,but most of the time Dijkstra gives a different path and the cost is smaller than the cost for the path UCS gives, is this right or there is something wrong with my code?

edit: here's the code for both algorithms implemented in java p.s the graph has two- way edges

public void UCS(Vertex source, Vertex goal) {

source.setDistance(0);
PriorityQueue<Vertex> queue = new PriorityQueue<Vertex>(20,
new Comparator<Vertex>(){

//override compare method
public int compare(Vertex i, Vertex j){
if(i.getDistance() > j.getDistance()){
return 1;
}

else if (i.getDistance() < j.getDistance()){
return -1;
}

else{
return 0;
}
}
}

);

Set<Vertex> explored = new HashSet<Vertex>();
boolean found = false;

//while frontier is not empty
do{

Vertex current = queue.poll();

if(current.getName().matches(goal.getName())){
found = true;

}

Edge e = findEdge(child, current);

double cost = e.getCost();
child.setDistance(current.getDistance() + cost);

if(!explored.contains(child) && !queue.contains(child)){

child.setDistance(cost+current.getDistance());
child.setPath(current);

}
else if((queue.contains(child))&&(child.getDistance()>(current.getDistance()+cost))){
child.setPath(current);

child.setDistance(current.getDistance()+cost);
// the next two calls decrease the key of the node in the queue
queue.remove(child);
}

}
}while(!queue.isEmpty()&&(found==false));



Dijkstra:

public void dijkstra(Vertex fromCity)
{
for (Vertex v : vertices)
{
v.setDistance(Integer.MAX_VALUE);
v.setPath(null);
}

Vertex fromLocal = findVertex(fromCity);
fromLocal.setDistance(0);

PriorityQueue<Vertex> heap = new PriorityQueue<>();

while (!heap.isEmpty() )
{
Vertex u = heap.poll();

{
double newDistance = u.getDistance() + e.getCost();

{
}
}
}
}
}
$$$$


As an example you can consider the graph $$G=(V,E)$$ with $$V=\{s,u,v\}$$, $$E=\{(s,u), (u,v), (s,v) \}$$ and weights $$w(s,u)=w(u,v)=1$$, $$w(s,v)=3$$.
The shortest path from $$s$$ to $$v$$ w.r.t. the edge weights is $$s \to u \to v$$ and has weight $$2$$. The shortest path w.r.t. the hop-distance (i.e., the number of used edges) is $$s\to v$$.
• @steven what u said is only true if the cost for all edges is the same, which is not the case here. A friend helped me figure out what is wrong with my code and i just had to delete  child.setDistance(current.getDistance() + cost); ` before the if statement. Apr 11 at 16:25