邻接矩阵为存储结构 | 实现图的深度、宽度优先遍历

本文介绍如何使用邻接矩阵作为存储结构,实现图的深度优先搜索(DFS)和宽度优先搜索(BFS)。通过mGraph.cpp、Queue.cpp和Queue.h等文件,详细阐述了遍历过程。

在这里插入图片描述
mGraph.cpp:

#include <iostream>
#include<stdio.h>
#include<stdlib.h>
#include "Queue.h"

using namespace std;

typedef int ElemType;
typedef struct{
   
   
    ElemType noEdge;                    //两顶点间没有边时的值
    int e;                             //当前边数
    int n;                              //当前顶点数
    ElemType **a;
}mGraph;                              //邻接矩阵的结构体

ElemType Init(mGraph *mg,int nSize,int noEdgeValue){
   
           //初始化函数
    int i,j;
    mg->noEdge = noEdgeValue;
    mg->n = nSize;
    mg->e = 0;              //初始化时没有边
    mg->a = (ElemType **)malloc(sizeof(ElemType *)*nSize);           //生成长度为n的一位指针数组
    if(!mg->a){
   
   
        cout<<"Run out of Memory!"<<endl;
        return 0;
    }
    for(i=0;i<mg->n;i++){
   
   
        mg->a[i] = (ElemType *)malloc(sizeof(ElemType)*(mg->n));
        for(j=0;j<mg->n;j++){
   
   
        mg->a[i][j] = mg->noEdge;
        }
        mg->a[i][i] = 0;
    }
    return 0;
}

void Destroy(mGraph *mg){
   
                      //释放内存函数
    int i;
    for(i=0;i<mg->n;i++){
   
   
        free(mg->a[i]);
    }
    free(mg->a);
}

ElemType Exist(mGraph *mg,int u,int v){
   
                                //查询是否有该边
    if(u==v||mg->a[u-1][v-1]==mg->noEdge||u<1||v<1||u>mg->n||v>mg->n){
   
   
        cout<<"Not Exist!"<<endl;
        return 0;
        };
        cout<<"Exist!"<<endl;
        return 0;
}

ElemType Insert(mGraph *mg,int u,int v,int w
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值