数据结构—prim最小生成树
原理:参考趣学数据结构
代码:
# include <stdio.h>
# include <stdlib.h>
# define N 100
# define elemType int
# define INF ( ( ( unsigned int ) ( - 1 ) ) >> 1 )
bool visited[ N] ;
typedef struct GraphMatrix { elemType vNode[ N] [ N] ; int vNum, eNum;
} GraphMatrix;
void initGMaxtix ( GraphMatrix & G) { printf ( "输入顶点数和边数\n" ) ; scanf_s ( "%d%d" , & G. vNum, & G. eNum) ; for ( int i = 0 ; i < G. vNum; i++ ) { for ( int j = 0 ; j < G. vNum; j++ ) { G. vNode[ i] [ j] = INF; } } printf ( "输入顶点v1到顶点v2和其边的权重\n" ) ; for ( int i = 0 ; i < G. eNum; i++ ) { int v1, v2, weights; scanf_s ( "%d%d%d" , & v1, & v2, & weights) ; G. vNode[ v1] [ v2] = weights; }
}
void print15 ( GraphMatrix G) { printf ( "邻接矩阵如下:\n" ) ; for ( int i = 0 ; i < G. vNum; i++ ) { for ( int j = 0 ; j < G. vNum; j++ ) { printf ( "%d " , G. vNode[ i] [ j] ) ; } printf ( "\n" ) ; }
}
void prim ( GraphMatrix G, int u0) { int lowcost[ N] , closeV[ N] ; for ( int i = 0 ; i < G. vNum; i++ ) { lowcost[ i] = G. vNode[ u0] [ i] ; closeV[ i] = u0; if ( u0 == i) { lowcost[ u0] = 0 ; } } visited[ u0] = true; printf ( "%d " , u0) ; for ( int k = 0 ; k < G. vNum - 1 ; k++ ) { int t = u0, Temp = INF; for ( int i = 0 ; i < G. vNum; i++ ) { if ( ! visited[ i] && Temp > lowcost[ i] ) { Temp = lowcost[ i] ; t = i; } } if ( t == u0) { break ; } visited[ t] = true; printf ( "%d " , t) ; for ( int i = 0 ; i < G. vNum; i++ ) { if ( ! visited[ i] && G. vNode[ t] [ i] < lowcost[ i] ) { lowcost[ i] = G. vNode[ t] [ i] ; closeV[ i] = t; } } } printf ( "\n哪些边有关系:\n" ) ; for ( int i = 0 ; i < G. vNum; i++ ) { if ( i != u0) { printf ( "%d---%d有边\n" , i, closeV[ i] ) ; } }
}
int main ( ) { GraphMatrix G; initGMaxtix ( G) ; print15 ( G) ; printf ( "\n" ) ; for ( int i = 0 ; i < G. vNum; i++ ) { visited[ i] = false; } printf ( "prim最小生成树\n" ) ; prim ( G, 0 ) ; printf ( "\n" ) ; system ( "pause" ) ; return 0 ;
}
测试截图:
时间复杂度O(n x n),空间复杂度O(n)
如果存在什么问题,欢迎批评指正!谢谢!