D
D
Davidaa_WoW2021-10-27 20:08:43
C++ / C#
Davidaa_WoW, 2021-10-27 20:08:43

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;
};


At the same time, I have the graph structure in the form of a one-dimensional array.
How to make Prim's algorithm for such a structure?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
R
Rsa97, 2021-10-27
@Rsa97

There will be no fundamental difference. The only difference is the way to iterate through the edges in search of the minimum weight.

U
User700, 2021-10-27
@User700

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;

Use std::forward_list

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question