第五章 图论 邻接矩阵存图

邻接矩阵存图

存储结构定义

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;
            }
    }
}
相关推荐
课堂剪切板2 小时前
ch03 部分题目思路
算法
山登绝顶我为峰 3(^v^)33 小时前
如何录制带备注的演示文稿(LaTex Beamer + Pympress)
c++·线性代数·算法·计算机·密码学·音视频·latex
Two_brushes.4 小时前
【算法】宽度优先遍历BFS
算法·leetcode·哈希算法·宽度优先
森焱森6 小时前
水下航行器外形分类详解
c语言·单片机·算法·架构·无人机
QuantumStack8 小时前
【C++ 真题】P1104 生日
开发语言·c++·算法
写个博客8 小时前
暑假算法日记第一天
算法
绿皮的猪猪侠8 小时前
算法笔记上机训练实战指南刷题
笔记·算法·pta·上机·浙大
hie988949 小时前
MATLAB锂离子电池伪二维(P2D)模型实现
人工智能·算法·matlab
杰克尼9 小时前
BM5 合并k个已排序的链表
数据结构·算法·链表
.30-06Springfield10 小时前
决策树(Decision tree)算法详解(ID3、C4.5、CART)
人工智能·python·算法·决策树·机器学习