I've looked through the questions on this already and still having some trouble. What exactly is going wrong in my attempt to implement Prim's algorithm? I feel like it is something to do with it not adding it to the spanning tree only if it is the minimum weight in the tree, but I'm failing to see how to implement this. Here is what I have tried so far and i will include the priority queues enqueue method at the top. It appears to add all of the vertices to the tree. The output I get for starting at the vertex 0 is the following..
(0, 5), (1, 5), (2, 5), (3, 5), (4, 5), (5, 5), (0, 1), (1, 1), (2, 1), (3, 1)
(4, 1), (0, 2), (2, 2), (3, 2), (4, 2), (0, 4), (3, 4), (4, 4)
def dequeue(self):
weight, data = self.queue.pop(0)
self.size -= 1
return data
def enqueue(self, data, weight):
curr_index = 0
while (curr_index < self.size and
self.queue[curr_index][WEIGHT] < weight):
curr_index += 1
self.queue.insert(curr_index, (weight, data))
self.size += 1
def add_edges(self, p_queue, vertex, vertices):
for i in range(len(self.adjacency_matrix)):
weight = self.adjacency_matrix[vertex][i]
if weight != 0:
p_queue.enqueue(vertex, weight)
if (i, vertex) not in vertices:
vertices.append((i, vertex))
return vertices
def init_pqu(self, p_queue, start_vertex):
for i in range(len(self.adjacency_matrix)):
weight = self.adjacency_matrix[start_vertex][i]
if weight != 0:
p_queue.enqueue(start_vertex, weight)
def prim(self, start_vertex):
vertices = []
priority_queue = pq.priority_queue()
self.init_pqu(priority_queue, start_vertex)
while len(priority_queue.queue) > 0:
source = priority_queue.dequeue()
vertices = self.add_edges(priority_queue, source, vertices)
return vertices