本文主要是介绍如何使用邻接矩阵和邻接表来表示无向图和有向图,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1. 无向图邻接矩阵表达:
#define MAX_VERTICES 100
typedef struct {
int matrix[MAX_VERTICES][MAX_VERTICES]; // 邻接矩阵
int numVertices; // 图中顶点数
} Graph;
// 初始化无向图
void initGraph(Graph* graph, int numVertices) {
graph->numVertices = numVertices;
for(int i = 0; i < numVertices; i++) {
for(int j = 0; j < numVertices; j++) {
graph->matrix[i][j] = 0; // 初始化所有边为0
}
}
}
// 添加无向图的边
void addEdge(Graph* graph, int v1, int v2) {
graph->matrix[v1][v2] = 1;
graph->matrix[v2][v1] = 1; // 由于是无向图,所以需要对称地设置另一条边
}
2. 有向图邻接表达:
#define MAX_VERTICES 100
typedef struct Node {
int dest; // 目标顶点
struct Node* next; // 下一个连接的边
} Node;
typedef struct {
Node* head[MAX_VERTICES]; // 邻接表的数组
int numVertices; // 图中顶点数
} Graph;
// 初始化有向图
void initGraph(Graph* graph, int numVertices) {
graph->numVertices = numVertices;
for(int i = 0; i < numVertices; i++) {
graph->head[i] = NULL; // 初始化邻接表为空
}
}
// 添加有向图的边
void addEdge(Graph* graph, int src, int dest) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->dest = dest;
newNode->next = graph->head[src];
graph->head[src] = newNode;
}
这篇关于如何使用邻接矩阵和邻接表来表示无向图和有向图的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!