Algorithm to find the shortest path