0

I implemented Dijkstra's algorithm to find the shortest path from the source vertex to all other vertices, and I also wanted to store what vertices make up each shortest path. I did this by keeping track of each vertex's predecessor. It is able to output the distances correctly, but as seen in the output below (ignore the candy stuff), two of the paths got switched (the path from the src to vertex 3 and the path from the src to vertex 4. I'm not sure why it is not outputting correctly? I must've done something wrong when storing the predecessors.

This is what the graph looks like.

Graph

The code in python...

from queue import PriorityQueue

class Graph:

    def __init__(self, num_of_vertices):
        self.v = num_of_vertices
        self.edges = [[-1 for i in range(num_of_vertices)] for j in range(num_of_vertices)]
        self.visited = []
        
    def add_edge(self, u, v, weight):
        self.edges[u][v] = weight
        self.edges[v][u] = weight
        
    def dijkstra(self, start_vertex):
        D = {v:float('inf') for v in range(self.v)}
        V = {v:None for v in range(self.v)}
        D[start_vertex] = 0
        
        pq = PriorityQueue()
        pq.put((0, start_vertex))
        
        AllPathsList = []
        
        while not pq.empty():
            (dist, current_vertex) = pq.get()
            self.visited.append(current_vertex)

            for neighbor in range(self.v):
                if self.edges[current_vertex][neighbor] != -1:
                    distance = self.edges[current_vertex][neighbor]
                    if neighbor not in self.visited:
                        old_cost = D[neighbor]
                        new_cost = D[current_vertex] + distance
                        if new_cost < old_cost:
                            pq.put((new_cost, neighbor))
                            D[neighbor] = new_cost
                            V[neighbor] = current_vertex          
            S = []
            u = current_vertex
            while V[u] != None:
                S.insert(0, u)
                u = V[u]
                
            S.insert(0, start_vertex)
            AllPathsList.append(S)
            
        return D, AllPathsList
        
def main():
    g = Graph(6)
    g.add_edge(0, 1, 4)
    g.add_edge(0, 2, 7)
    g.add_edge(1, 2, 11)
    g.add_edge(1, 3, 20)
    g.add_edge(3, 4, 5)
    g.add_edge(3, 5, 6)
    g.add_edge(2, 3, 3)
    g.add_edge(2, 4 ,2)
#                         0, 1, 2, 3, 4, 5
    CandyPerVertexList = [0, 5, 4, 7, 8, 2]
    
    D, AllPathsList = g.dijkstra(0)

    for vertex in range(len(D)):
        print("Distance from my house to house #", vertex, "is:", D[vertex], "min")
        print("Particular path is:", AllPathsList[vertex])
        
        CandySum = 0
        for num in range(len(AllPathsList[vertex])):
            CandySum = CandySum + CandyPerVertexList[AllPathsList[vertex][num]]
        print("Candy amount for this path: ", CandySum)
        print()
main()

And the output

Distance from my house to house # 0 is: 0 min
Particular path is: [0]
Candy amount for this path:  0

Distance from my house to house # 1 is: 4 min
Particular path is: [0, 1]
Candy amount for this path:  5

Distance from my house to house # 2 is: 7 min
Particular path is: [0, 2]
Candy amount for this path:  4

Distance from my house to house # 3 is: 10 min
Particular path is: [0, 2, 4]
Candy amount for this path:  12

Distance from my house to house # 4 is: 9 min
Particular path is: [0, 2, 3]
Candy amount for this path:  11

Distance from my house to house # 5 is: 16 min
Particular path is: [0, 2, 3, 5]
Candy amount for this path:  13
2
  • Could it be that you are mutating the paths and the ones you add to your list that you return at the end are not independent copies but just lists that are changed but next iterations of the algorithm? Commented Dec 1, 2021 at 21:56
  • @user1984 What should I change to prevent this? Commented Dec 1, 2021 at 22:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.