图的邻接矩阵
数据结构定义
# define MAXV 50 ;
typedef struct {
int vex[ MAX] ;
int edge[ MAXV] [ MAXV] ;
int edgeNum, vexNum;
} MGraph;
初始化
void Matrix_Init ( MGraph * Mgraph) {
int v1, v2;
printf ( "请输入顶点数和边数:" ) ;
scanf ( "%d%d" , & Mgraph-> vexNum, & Mgraph-> edgeNum) ;
printf ( "请输入每个顶点的值(一次性输入):" ) ;
for ( int i = 0 ; i < Mgraph-> vexNum; i++ )
{
scanf ( "%d" , & Mgraph-> vex[ i] ) ;
}
for ( int i = 0 ; i < Mgraph-> edgeNum; i++ )
{
for ( int j = 0 ; j < Mgraph-> edgeNum; j++ )
{
Mgraph-> edge[ i] [ j] = 0 ;
}
}
for ( int i = 0 ; i < Mgraph-> edgeNum; i++ )
{
printf ( "请输入有边相连的两个顶点的序号(输入一对就回车):" ) ;
scanf ( "%d%d" , & v1, & v2) ;
Mgraph-> edge[ v1 - 1 ] [ v2 - 1 ] = 1 ;
Mgraph-> edge[ v2 - 1 ] [ v1 - 1 ] = 1 ;
}
}
2021年408算法题
int IsExistEL ( MGraph G) {
int count = 0 ;
for ( int i = 0 ; i< G. numVertices; i++ ) {
degree = 0 ;
for ( int j = 0 ; j< G. numEdges; j++ ) {
degree+= G. Edge[ i] [ j] ;
}
if ( degree% 2 == 1 ) {
count++ ;
}
}
if ( count == 0 || count == 2 ) {
return 1 ;
} else {
return 0 ;
}
}
2023年408算法题
int printVertices ( MGraph G) {
int count = 0 ;
for ( int i = 0 ; i< G. numVertices; i++ ) {
int indegree = 0 ;
int outdegree = 0 ;
for ( int j = 0 ; j< G. numEdges; j++ ) {
outdegree+= G. Edge[ i] [ j] ;
}
fot ( int j = 0 ; j< G. numEdges; j++ ) {
indegree+= G. Edge[ j] i] ;
}
if ( outdegree> indegree) {
printf ( "%c" , G. VerticesList[ i] ) ;
count++ ;
}
}
return count;
}
邻接表
数据结构定义
# define MAXV 50 ;
typedef struct ArcNode {
int adjvex;
struct ArcNode * nextArc;
} ArcNode;
typedef struct {
int vex;
ArcNode* firstArc;
} VertexNode;
typedef struct {
VertexNode adjlist[ MAXV] ;
int vexNum, arcNum;
} ALGraph;
初始化
void AdjList_Init ( ALGraph & ALgraph) {
int v1, v2;
ArcNode * pNew1, * pNew2;
printf ( "请输入顶点数和边数:" ) ;
scanf ( "%d%d" , & ALgraph. vexNum, & ALgraph. arcNum) ;
printf ( "请输入每个顶点的值:" ) ;
for ( int i = 0 ; i < ALgraph. vexNum; i++ )
{
scanf ( "%d" , & ALgraph. adjlist[ i] . vex) ;
ALgraph. adjlist[ i] . firstArc = NULL ;
}
for ( int i = 0 ; i < ALgraph. arcNum; i++ )
{
printf ( "请输入有边的两个顶点:" ) ;
scanf ( "%d%d" , & v1, & v2) ;
pNew1 = ( ArcNode* ) malloc ( sizeof ( ArcNode) ) ;
pNew1-> adjvex = v2 - 1 ;
pNew1-> nextArc = ALgraph. adjlist[ v1 - 1 ] . firstArc;
ALgraph. adjlist[ v1 - 1 ] . firstArc = pNew1;
pNew2 = ( ArcNode* ) malloc ( sizeof ( ArcNode) ) ;
pNew2-> adjvex = v1 - 1 ;
pNew2-> nextArc = ALgraph. adjlist[ v2 - 1 ] . firstArc;
ALgraph. adjlist[ v2 - 1 ] . firstArc = pNew1;
}
}
2021年408算法题(邻接表改编版)
2023年408算法题(邻接表改编版)