以下是我使用 Prim 算法将连通图转换为 MST 的伪代码。然而,我得到的复杂度是 n^3 而不是 n^2。请帮我找出不需要的步骤。我有一个邻接矩阵“a”来存储图边的权重,一个二维矩阵“检查”存储树中已经存在的顶点“1”和剩余的“0”。
另请注意,这也可以在 nlog(n) 中完成,但我不想引用任何现有的伪代码并想自己尝试。我将不胜感激优化我自己的方法的答案。
Initialize check. //check[0][1]==1
while(--no_of_vertices)
{
minimum_outer = infinite
for(i from 1 to no_of_vertices)
{
minimum_inner = infinite
select i from check having value 1
for(j from 1 to no_of_vertices )
{
select j from check having value 0
if(a[i-j] < minimum_inner)
minimum_inner = a[i-j]
temp_j = j;
}
if(minimum_inner<minimum_outer)
{
minimum_outer = minimum_inner
final_i = i
final_j = temp_j
}
}
//until here basically what I have done is, selected an i-j with lowest
//weight where "i" is chosen from vertices already in MST and "j" from
//remaining vertices
check[final_j][1] = 1
print final_i - final_j
cost_of_mst += a[final_i][final_j]
}