File tree Expand file tree Collapse file tree 1 file changed +20
-21
lines changed Expand file tree Collapse file tree 1 file changed +20
-21
lines changed Original file line number Diff line number Diff line change 11class Solution :
2- def prim (self , graph ):
2+ # graph 为图的邻接矩阵,start 为起始顶点
3+ def prim (self , graph , start ):
34 size = len (graph )
45 vis = set ()
56 dist = [float ('inf' ) for _ in range (size )]
67
7- ans = 0
8- pos = 0
9- dist [pos ] = 0
10- vis .add (pos )
8+ ans = 0 # 最小生成树的边权和
9+ dist [start ] = 0 # 初始化起始顶点到起始顶点的边权值为 0
1110
12- for i in range (1 , size ):
13- if 0 in graph and i in graph [0 ]:
14- dist [ i ] = graph [ 0 ][ i ]
11+ for i in range (1 , size ): # 初始化起始顶点到其他顶点的边权值
12+ dist [ i ] = graph [start ][ i ]
13+ vis . add ( start ) # 将 start 顶点标记为已访问
1514
16- for i in range (size - 1 ):
17- cur_min = float ('inf' )
18- pos = - 1
19- for j in range (size ):
20- if j not in vis and dist [j ] < cur_min :
21- cur_min = dist [j ]
22- pos = j
23- if pos == - 1 :
15+ for _ in range (size - 1 ):
16+ min_dis = float ('inf' )
17+ min_dis_pos = - 1
18+ for i in range (size ):
19+ if i not in vis and dist [i ] < min_dis :
20+ min_dis = dist [i ]
21+ min_dis_pos = i
22+ if min_dis_pos == - 1 : # 没有顶点可以加入 MST,图 G 不连通
2423 return - 1
25- ans += cur_min
26- vis .add (pos )
27- for j in range (size ):
28- if j not in vis and dist [j ] > graph [pos ][ j ]:
29- dist [j ] = graph [pos ][ j ]
24+ ans += min_dis # 将顶点加入 MST,并将边权值加入到答案中
25+ vis .add (min_dis_pos )
26+ for i in range (size ):
27+ if i not in vis and dist [i ] > graph [min_dis_pos ][ i ]:
28+ dist [i ] = graph [min_dis_pos ][ i ]
3029 return ans
3130
3231points = [[0 ,0 ]]
You can’t perform that action at this time.
0 commit comments