图的遍历(BFS,DFS)

本文介绍了在数据结构课程中用C++实现图的两种遍历方法——广度优先搜索(BFS)和深度优先搜索(DFS)。通过邻接矩阵和邻接表两种存储方式,实现了图的遍历。BFS利用队列进行,而DFS则采用递归方法。代码示例展示了如何构造和遍历图。
摘要由CSDN通过智能技术生成

前言:在数据结构课程中,用C++封装了一些经典的算法,所以特地开一个个人分类来记录这些算法,以便将来用到的时候能够使我回忆起来,或者当做模板使用(另一方面也将书本上的代码的一些错误改正过来,方便以后的同学参考)。

首先是第三章的图的作业,图有两种存储方法,一种是用邻接矩阵来存图(主要用于稠密图),另一种是用邻接表来存图(主要用于稀疏图)。两种存图的方式不同,但是可以通过重写虚函数,使两种方式对图的操作的函数都一样,这样就便于之后在图上的各种算法的实现(比如最小生成树,最短路,拓补排序)

这次作业是封装图的类型以及用BFS,DFS 来遍历图。BFS用队列来实现,DFS则用递归来实现。

下面是我这段代码的构造的图:




下面是代码


1、邻接矩阵实现:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<queue>
#include<stack>
#include<algorithm>
#include<cstdlib>
using namespace std;
const int INF = 0x7fffffff;
//边类型
template <class EdgeType>
class Edge
{
public:
    int start,endd;
    EdgeType weight;
    Edge():start(-1),endd(-1),weight(-1){}
    Edge(int s,int e,int w=-1):start(s),endd(e),weight(w){}
    bool operator < (const Edge<EdgeType> e) const {
        return this->weight > e.weight;
    }
};

//图的抽象数据类型
template <class EdgeType>
class Graph
{
public:
    int numv,nume;
    bool *mark;

    //构造函数
    Graph(int num):numv(num),nume(0) {
        mark = new bool[num+1];
        memset(mark,false,sizeof(mark));
    }

    //析构函数
    ~Graph() {
        delete []mark;
    }
    virtual Edge<EdgeType> FirstEdge(int vertex)=0;
    virtual Edge<EdgeType> NextEdge(Edge<EdgeType> edge)=0;
    virtual void addEdge(int s,int e,EdgeType w)=0;
//    virtual void deleEdge(int s,int e)=0;

    //判断该边是否为该图的边
    bool IsEdge(Edge<EdgeType> edge) {
        if(edge.weight == -1) {
            return false;
        }
        return true;
    }
};



//邻接矩阵类型
template<class EdgeType>
class MatGraph: public Graph<EdgeType>
{
private:
    int **matrix
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值