DFS

从图中某个顶点V0 出发,访问此顶点,然后依次从V0的各个未被访问的邻接点出发深度优先搜索遍历图,直至图中所有和V0有路径相通的顶点都被访问到(使用堆栈).

//使用邻接矩阵存储的无向图的深度优先遍历
template <typename Type>
void Graph<Type>::DFS()
{
    stack<int> iStack;

    showVertex(0);
    vertexList[0]->wasVisted = true;
    iStack.push(0);

    while (!iStack.empty())
    {
        int top = iStack.top();
        int v = getAdjUnvisitedVertex(top);
        if (v == -1)
        {
            iStack.pop();
        }
        else
        {
            showVertex(v);
            vertexList[v]->wasVisted = true;
            iStack.push(v);
        }
    }

    //使其还可以再深/广度优先搜索
    for (int i = 0; i < nVerts; ++i)
        vertexList[i]->wasVisted = false;
}

BFS

从图中的某个顶点V0出发,并在访问此顶点之后依次访问V0的所有未被访问过的邻接点,之后按这些顶点被访问的先后次序依次访问它们的邻接点,直至图中所有和V0有路径相通的顶点都被访问到.

若此时图中尚有顶点未被访问,则另选图中一个未曾被访问的顶点作起始点,重复上述过程,直至图中所有顶点都被访问到为止(使用队列)。

//使用邻接矩阵存储的无向图的广度优先遍历
template <typename Type>
void Graph<Type>::BFS()
{
    queue<int> iQueue;

    showVertex(0);
    vertexList[0]->wasVisted = true;
    iQueue.push(0);

    while (!iQueue.empty())
    {
        int front = iQueue.front();
        iQueue.pop();
        int v = getAdjUnvisitedVertex(front);
        while (v != -1)
        {
            showVertex(v);
            vertexList[v]->wasVisted = true;
            iQueue.push(v);
            v = getAdjUnvisitedVertex(front);
        }
    }

    for (int i = 0; i < nVerts; ++i)
        vertexList[i]->wasVisted = false;
}

附-完整代码

const int MAX_VERTS = 20;
//顶点
template <typename Type>
class Vertex
{
public:
    Vertex(const Type &_node = Type())
        : node(_node), wasVisted(false) {}

public:
    bool wasVisted;	//增加一个访问位
    Type node;
};
//图
template <typename Type>
class Graph
{
public:
    Graph();
    ~Graph();

    void addVertex(const Type &vertex);
    void addEdge(int start, int end);
    void printMatrix();
    void showVertex(int v);
    void DFS();
    void BFS();

private:
    int getAdjUnvisitedVertex(int v);

private:
    Vertex<Type>* vertexList[MAX_VERTS];
    int nVerts;
    int adjMatrix[MAX_VERTS][MAX_VERTS];
};
template <typename Type>
void Graph<Type>::DFS()
{
    stack<int> iStack;

    showVertex(0);
    vertexList[0]->wasVisted = true;
    iStack.push(0);

    while (!iStack.empty())
    {
        int top = iStack.top();
        int v = getAdjUnvisitedVertex(top);
        if (v == -1)
        {
            iStack.pop();
        }
        else
        {
            showVertex(v);
            vertexList[v]->wasVisted = true;
            iStack.push(v);
        }
    }

    //使其还可以再深度优先搜索
    for (int i = 0; i < nVerts; ++i)
        vertexList[i]->wasVisted = false;
}

template <typename Type>
void Graph<Type>::BFS()
{
    queue<int> iQueue;

    showVertex(0);
    vertexList[0]->wasVisted = true;
    iQueue.push(0);

    while (!iQueue.empty())
    {
        int front = iQueue.front();
        iQueue.pop();
        int v = getAdjUnvisitedVertex(front);
        while (v != -1)
        {
            showVertex(v);
            vertexList[v]->wasVisted = true;
            iQueue.push(v);
            v = getAdjUnvisitedVertex(front);
        }
    }

    for (int i = 0; i < nVerts; ++i)
        vertexList[i]->wasVisted = false;
}
//获取下一个尚未访问的连通节点
template <typename Type>
int Graph<Type>::getAdjUnvisitedVertex(int v)
{
    for (int j = 0; j < nVerts; ++j)
    {
        //首先是邻接的, 并且是未访问过的
        if ((adjMatrix[v][j] == 1) &&
                (vertexList[j]->wasVisted == false))
            return j;
    }
    return -1;
}
//打印节点信息
template <typename Type>
void Graph<Type>::showVertex(int v)
{
    cout << vertexList[v]->node << ' ';
}

template <typename Type>
Graph<Type>::Graph():nVerts(0)
{
    for (int i = 0; i < MAX_VERTS; ++i)
        for (int j = 0; j < MAX_VERTS; ++j)
            adjMatrix[i][j] = 0;
}
template <typename Type>
Graph<Type>::~Graph()
{
    for (int i = 0; i < nVerts; ++i)
        delete vertexList[i];
}
template <typename Type>
void Graph<Type>::addVertex(const Type &vertex)
{
    vertexList[nVerts ++] = new Vertex<Type>(vertex);
}
template <typename Type>
void Graph<Type>::addEdge(int start, int end)
{
    //无向图
    adjMatrix[start][end] = 1;
    adjMatrix[end][start] = 1;
}
template <typename Type>
void Graph<Type>::printMatrix()
{
    for (int i = 0; i < nVerts; ++i)
    {
        for (int j = 0; j < nVerts; ++j)
            cout << adjMatrix[i][j] << ' ';
        cout << endl;
    }
}

//测试代码
int main()
{
    Graph<char> g;
    g.addVertex('A');   //0
    g.addVertex('B');   //1
    g.addVertex('C');   //2
    g.addVertex('D');   //3
    g.addVertex('E');   //4

    g.addEdge(0, 1);    //A-B
    g.addEdge(0, 3);    //A-D
    g.addEdge(1, 0);    //B-A
    g.addEdge(1, 4);    //B-E
    g.addEdge(2, 4);    //C-E
    g.addEdge(3, 0);    //D-A
    g.addEdge(3, 4);    //D-E
    g.addEdge(4, 1);    //E-B
    g.addEdge(4, 2);    //E-C
    g.addEdge(4, 3);    //E-D

    g.printMatrix();

    cout << "DFS: ";
    g.DFS();
    cout << "\nBFS: ";
    g.BFS();
    return 0;
}

数据结构基础(21) --DFS与BFS的更多相关文章

  1. Java数据结构——图的DFS和BFS

    1.图的DFS: 即Breadth First Search,深度优先搜索是从起始顶点开始,递归访问其所有邻近节点,比如A节点是其第一个邻近节点,而B节点又是A的一个邻近节点,则DFS访问A节点后再访 ...

  2. [数据结构]图的DFS和BFS的两种实现方式

    深度优先搜索 深度优先搜索,我们以无向图为例. 图的深度优先搜索(Depth First Search),和树的先序遍历比较类似. 它的思想:假设初始状态是图中所有顶点均未被访问,则从某个顶点v出发, ...

  3. 算法与数据结构基础 - 深度优先搜索(DFS)

    DFS基础 深度优先搜索(Depth First Search)是一种搜索思路,相比广度优先搜索(BFS),DFS对每一个分枝路径深入到不能再深入为止,其应用于树/图的遍历.嵌套关系处理.回溯等,可以 ...

  4. 【数据结构与算法笔记04】对图搜索策略的一些思考(包括DFS和BFS)

    图搜索策略 这里的"图搜索策略"应该怎么理解呢? 首先,是"图搜索",所谓图无非就是由节点和边组成的,那么图搜索也就是将这个图中所有的节点和边都访问一遍. 其次 ...

  5. 算法与数据结构基础 - 广度优先搜索(BFS)

    BFS基础 广度优先搜索(Breadth First Search)用于按离始节点距离.由近到远渐次访问图的节点,可视化BFS 通常使用队列(queue)结构模拟BFS过程,关于queue见:算法与数 ...

  6. Clone Graph leetcode java(DFS and BFS 基础)

    题目: Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors. ...

  7. 数据结构(12) -- 图的邻接矩阵的DFS和BFS

    //////////////////////////////////////////////////////// //图的邻接矩阵的DFS和BFS ////////////////////////// ...

  8. 数据结构(11) -- 邻接表存储图的DFS和BFS

    /////////////////////////////////////////////////////////////// //图的邻接表表示法以及DFS和BFS //////////////// ...

  9. 列出连通集(DFS及BFS遍历图) -- 数据结构

    题目: 7-1 列出连通集 (30 分) 给定一个有N个顶点和E条边的无向图,请用DFS和BFS分别列出其所有的连通集.假设顶点从0到N−1编号.进行搜索时,假设我们总是从编号最小的顶点出发,按编号递 ...

随机推荐

  1. Java第6次实验提纲(异常)

    PTA与参考资料 题集:集合 异常实验文件 第1次实验 1.1 7-1 常用异常 如何进行强制转换 如何捕获多种类型的异常 1.2 7-2 使用异常机制处理异常输入 在哪里加catch 1.3 7-3 ...

  2. windows下python3.5使用pip离线安装whl包

    0. 绪论 Windows离线断网环境下安装Python包,配置环境,准备用来生成word模版.姑且记录一下 生产环境 : windows 7 windows10 python 3.5.2 pip 1 ...

  3. android addCategory()等说明

    一.隐式意图介绍 显式意图我们前面已经提到,形如: Intent intent = new Intent(); intent.setClass(this,Other.class);//此句表示显式意图 ...

  4. Netty 4源码解析:请求处理

    Netty 4源码解析:请求处理 通过之前<Netty 4源码解析:服务端启动>的分析,我们知道在最前端"扛压力"的是NioEventLoop.run()方法.我们指定 ...

  5. Unity 资源管理插件

    之所以写这个插件呢,就是为了方便整理项目中的资源文件,我记得之前好像也用了这么一个插件,但是也没去找,还是自己动手写一个吧,需要什么功能就看自己的需求. 在项目的过程中呢,已经写了一个插件来管理材质, ...

  6. JVM垃圾回收总结

    来自Oracle官方文档,对JVM GC知识整理的清晰易懂,查资料还是看官方的好! 1 GC步骤简述 步骤1:标记 (Marking) 根据对象引用关系,将未被任何对象引用的对象实例标记出来,如下图中 ...

  7. EBS销售订单挑库发放处理程序

    来自:http://blog.csdn.net/cunxiyuan108/article/details/6014769 在EBS实施中,经常遇到从外部传进来一个被登记的销售订单,需要通过程序进行销售 ...

  8. 手把手图文并茂教你用Android Studio编译FFmpeg库并移植

    转载请把头部出处链接和尾部二维码一起转载,本文出自逆流的鱼yuiop:http://blog.csdn.net/hejjunlin/article/details/52661331 之前曾写过一篇&l ...

  9. 4-sum问题

    给定一个整数数组,判断能否从中找出4个数a.b.c.d,使得他们的和为0,如果能,请找出所有满足和为0个4个数对. #define SIZE 10 void judgeAndPut(int* arr, ...

  10. 获取imageView的图和背景图

    img1和img2都是ImageView,要把img1中的图片显示到img2中 前景(对应src属性) img2.setImageDrawable(img1.getDrawable()); 背景(对应 ...