第五章 图论 邻接矩阵存图

邻接矩阵存图

存储结构定义

cpp 复制代码
#define MaxSize 10 // 图中最多顶点个数
typedef char DataType;
typedef strcut{
    DataType vertex[MaxSize];
    int edge[MaxSize][MaxSize];
    int vertexNum, edgeNum;
} Mgraph;

建图

cpp 复制代码
void CreateGraph(Mgraph *G, DataType a[], int n, int m){
    G->vertex=n, G->edgeNum=m;
    for(int i=0; i<n; i++) G->vertex[i]=a[i];
    for(int i=0; i<m; i++) for(int j=0; j<m; j++) G->edge[i][j]=0; // 初始化
    for(int i=0; i<m; i++){
        int x, y;
        scanf("%d%d", &x, &y);
        G->edge[x][y]=G->edge[y][x]=1; // 存边
    }
}

遍历

  • dfs
cpp 复制代码
void dfs(Mgraph *G, int u){ // 全局变量数组 st[n] 初始化为 0
    printf("%c ", G->vertex[u]);
    st[u]=true;
    for(int v=0; v<G->vertexNum; v++){
        if(G->vertex[u][v]==1 && st[v]==0)
            dfs(G, v);
    }
}
  • bfs
cpp 复制代码
void bfs(Mgraph *G, int root){ // 全局变量数组 st[n] 初始化为 0
    int Q[MaxSize];
    int front=-1, rear=-1;
    printf("%c ", G->vertex[root]);
    Q[++rear]=root, st[root]=1;
    while(front != rear){
        int u=Q[front++];
        for(int v=0; v<G->vertexNum; v++)
            if(G->edge[i][j]==1 && st[v]==0){
                printf("%c ", G->vertex[v]);
                Q[++rear]=v, st[v]=1;
            }
    }
}
相关推荐
海石1 小时前
单调栈复健,顺便,牺牲一下吧,空间复杂度!一切献给AC
算法·leetcode
海石1 小时前
JS击败94%,Hard题想不到动态规划,那就用数组和栈试试
算法·leetcode
山峰哥2 小时前
数据库工程与SQL优化实战指南‌
数据库·sql·oracle·深度优先·宽度优先
码少女2 小时前
数据结构——希尔排序
数据结构·排序算法
星子yu2 小时前
【学习】怎么学好数据结构
数据结构·学习
学究天人3 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷7)
线性代数·矩阵·动态规划·概率论·图论·抽象代数·拓扑学
alphaTao3 小时前
LeetCode 每日一题 2026/7/6-2026/7/12
算法·leetcode
想吃火锅10053 小时前
【leetcode】56.合并区间js
算法·leetcode·职场和发展
imuliuliang3 小时前
可合并堆在多任务调度中的优势与实现技巧7
算法
学究天人3 小时前
数学公理体系大全:Comprehensive Collection of Mathematical Axiom Systems(卷6)
网络·算法·数学建模·动态规划·几何学·图论·拓扑学