mafulechka
July 29, 2019, 12:57 p.m.

Algorithm Prima

Prim's algorithm is a minimum spanning tree algorithm that takes a graph as input and finds a subset of the edges of that graph that forms a tree that includes each vertex and also has the minimum sum of weights among all trees that can be formed from the graph.


How Prim's algorithm works

It falls under a class of algorithms called "greedy" algorithms that find a local optimum in the hope of finding a global optimum.

We start at one vertex and keep adding edges with the lowest weight until we reach our goal.

The steps to implement Prim's algorithm are as follows:

  1. Initialize a minimum spanning tree with an arbitrary vertex.
  2. Find all edges that connect the tree to new vertices, find the minimum and add it to the tree.
  3. Keep repeating step 2 until you get the minimum spanning tree.

Prima algorithm example

Prim's algorithm. Pseudocode.

The pseudocode for Prim's algorithm shows how we create two sets of vertices U and VU. U contains a list of vertices that have been visited, and VU a list of vertices that have not been visited. One by one, we move vertices from set VU to set U, connecting the edge with the lowest weight.

Implementing Prim's Algorithm in C++

The program below implements Prim's algorithm in C++. Although it uses an adjacency matrix to represent the graph, this algorithm can also be implemented using an adjacency list to improve its efficiency.

  1. #include <iostream>
  2. #include <cstring>
  3. using namespace std;
  4.  
  5. #define INF 9999999
  6.  
  7. // number of vertices in grapj
  8. #define V 5
  9.  
  10. // create a 2d array of size 5x5
  11. //for adjacency matrix to represent graph
  12.  
  13. int G[V][V] = {
  14. {0, 9, 75, 0, 0},
  15. {9, 0, 95, 19, 42},
  16. {75, 95, 0, 51, 66},
  17. {0, 19, 51, 0, 31},
  18. {0, 42, 66, 31, 0}
  19. };
  20.  
  21. int main () {
  22.  
  23. int no_edge; // number of edge
  24.  
  25. // create a array to track selected vertex
  26. // selected will become true otherwise false
  27. int selected[V];
  28.  
  29. // set selected false initially
  30. memset (selected, false, sizeof (selected));
  31.  
  32. // set number of edge to 0
  33. no_edge = 0;
  34.  
  35. // the number of egde in minimum spanning tree will be
  36. // always less than (V -1), where V is number of vertices in
  37. //graph
  38.  
  39. // choose 0th vertex and make it true
  40. selected[0] = true;
  41.  
  42. int x; // row number
  43. int y; // col number
  44.  
  45. // print for edge and weight
  46. cout << "Edge" << " : " << "Weight";
  47. cout << endl;
  48. while (no_edge < V - 1) {
  49.  
  50. //For every vertex in the set S, find the all adjacent vertices
  51. // , calculate the distance from the vertex selected at step 1.
  52. // if the vertex is already in the set S, discard it otherwise
  53. //choose another vertex nearest to selected vertex at step 1.
  54.  
  55. int min = INF;
  56. x = 0;
  57. y = 0;
  58.  
  59. for (int i = 0; i < V; i++) {
  60. if (selected[i]) {
  61. for (int j = 0; j < V; j++) {
  62. if (!selected[j] && G[i][j]) { // not in selected and there is an edge
  63. if (min > G[i][j]) {
  64. min = G[i][j];
  65. x = i;
  66. y = j;
  67. }
  68.  
  69. }
  70. }
  71. }
  72. }
  73. cout << x << " - " << y << " : " << G[x][y];
  74. cout << endl;
  75. selected[y] = true;
  76. no_edge++;
  77. }
  78.  
  79. return 0;
  80. }

When we run the above code, we get output like this:

  1. Edge : Weight
  2. 0 - 1 : 9
  3. 1 - 3 : 19
  4. 3 - 4 : 31
  5. 3 - 2 : 51

Prim's algorithm vs Kraskal's

Kruskal's algorithm is another popular minimum spanning tree algorithm that uses a different logic to find the MST graph. Instead of starting at the top, Kruskal's algorithm sorts all edges from low weight to high weight and continues adding the lowest edges, ignoring those edges that create a loop.

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html