graph - 如何为图的每个节点打印 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);
}
解决方案
推荐阅读
- python - Pytest AttributeError:“函数”对象没有属性“test_func”
- javascript - 凯撒密码 - 空格和其他字符
- xcode - 在 bash 脚本开始时调用终端输入
- c - 如何操作字符串以将它们的一部分存储为变量?
- html - 如何在同一行对齐 2 个表格?
- c++ - 为什么我的字符串函数不返回任何内容?
- android - 可以使用
在 RecyclerView 的 ViewHolder 布局内标记? - android - Volley request JSONArray should be recognized if it was empty
- javascript - 增加对象数量而不是在数组中创建新对象
- erlang - 在 Erlang ODBC 中处理 `nvarchar(MAX)` 问题的任何解决方法?