首页 > 解决方案 > 如何为图的每个节点打印 MST 树?

问题描述

我正在学习数据结构,现在我在 Prim 的算法。我想修改以下算法以打印图的每个节点或至少为指定节点的 MST 树,但我真的不知道从哪里开始。

我将不胜感激。谢谢!

int minKey(int key[], bool mstSet[])
{
    // Initialize min value  
    int min = INT_MAX, min_index;

    for (int v = 0; v < V; v++)
        if (mstSet[v] == false && key[v] < min)
            min = key[v], min_index = v;

    return min_index;
}

// function to print the constructed MST   
void printMST(int parent[], int graph[V][V])
{
    cout << "Edge \tWeight\n";
    for (int i = 1; i < V; i++)
        cout << parent[i] << " - " << i << " \t" << graph[i][parent[i]] << " \n";
}
void primMST(int graph[V][V])
{ 
    int parent[V];

    // Key values used to pick minimum weight edge  
    int key[V];

    // To represent set of vertices not yet included in MST  
    bool mstSet[V];

    for (int i = 0; i < V; i++)
        key[i] = INT_MAX, mstSet[i] = false;

    // Make key 0 so that this vertex is picked as first vertex.  
    key[0] = 0;
    parent[0] = -1; // First node is always root of MST  

    for (int count = 0; count < V - 1; count++)
    {
        // Pick the minimum key vertex 
        int u = minKey(key, mstSet);

        // Add the picked vertex to the MST Set  
        mstSet[u] = true;

        // Update key value and parent index of  
        // the adjacent vertices of the picked vertex.   
        for (int v = 0; v < V; v++)   
            if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
                parent[v] = u, key[v] = graph[u][v];
    }

    printMST(parent, graph);
}

标签: graphminimum-spanning-treeprims-algorithm

解决方案


推荐阅读