第五章 图论 邻接矩阵存图

邻接矩阵存图

存储结构定义

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;
            }
    }
}
相关推荐
不見星空8 分钟前
leetcode 每日一题 1865. 找出和为指定值的下标对
算法·leetcode
我爱Jack19 分钟前
时间与空间复杂度详解:算法效率的度量衡
java·开发语言·算法
☆璇41 分钟前
【数据结构】栈和队列
c语言·数据结构
DoraBigHead2 小时前
小哆啦解题记——映射的背叛
算法
Heartoxx2 小时前
c语言-指针与一维数组
c语言·开发语言·算法
孤狼warrior2 小时前
灰色预测模型
人工智能·python·算法·数学建模
京东云开发者2 小时前
京东零售基于国产芯片的AI引擎技术
算法
chao_7894 小时前
回溯题解——子集【LeetCode】二进制枚举法
开发语言·数据结构·python·算法·leetcode
十盒半价4 小时前
从递归到动态规划:手把手教你玩转算法三剑客
javascript·算法·trae
GEEK零零七4 小时前
Leetcode 1070. 产品销售分析 III
sql·算法·leetcode