Answer the question
In order to leave comments, you need to log in
How to implement Prim's algorithm for a graph as a list of adjacent vertices?
On the net I saw many different Prim's algorithms for a graph, which is implemented as an adjacency matrix. However, I have it in the form of a list of adjacent vertices. The structure is as follows:
struct list {
int data;
int firstPeak;
int secondPeak;
list* next = 0;
};
struct graph {
int data;
list* List = new list;
};
Answer the question
In order to leave comments, you need to log in
There will be no fundamental difference. The only difference is the way to iterate through the edges in search of the minimum weight.
1) I suppose it is optimal to pre-sort the edges by weight from the minimum.
2) You still need to store a lot of vertices. Good for this storage in the form of a "bitmap", ie. array of bits (array of bool): std::vector of bool, let's call the array IN(n), because you still have to add them all. n is the number of vertices (and the size of the array).
3) Also, the result will be presented as a set of edges. You can also use an edge list to represent the rest of the tree.
4) Algorithm.
If n == 0 then return.
IN[0] = true; v_count = 1.
While v_count is less than n
Looking for the first edge from the list that connects vertices i and j (or vice versa!), provided IN[i] & !IN[j]: add it to the response list, IN[j] = true, ++v_count.
PS
And what is this for?
list* List = new list;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question