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;
}