如何使用邻接矩阵和邻接表来表示无向图和有向图

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

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值