图的遍历-广度优先和深度优先遍历

图的遍历

  1. 概念
    从给定图中任意指定的顶点出发,按照某种搜索方法沿着图的边访问图中的所有顶点,使每个顶点仅被访问一次,这个过程就是图的遍历。方法有两种:深度优先遍历(DFS)和广度优先遍历(BFS)。

  2. 《图的遍历-广度优先和深度优先遍历》
    从顶点0开始进行深度优先遍历,可以得到如下访问序列:0 1 2 4 3 或 0 3 2 4 1。
    从顶点0开始进行广度优先遍历,可以得到如下访问序列:0 1 3 2 4或 0 3 1 2 4。

  3. 上代码

#include<stdio.h>
#include <malloc.h>
#include <iostream>
using namespace std;
#define maxv 5

//图的邻接矩阵
typedef struct
{
    int edges[maxv][maxv];
    int n;//n个顶点
}MGraph;

//图的邻接表
typedef struct Node//边节点
{
    int adjvex;//边的终点编号
    Node *nextarc;
    //int info;边的信息,例如权值
}ArcNode;

typedef struct//表头
{
    int data;
    ArcNode *firstarc;
}VNode;

typedef struct
{
    VNode adjlist[maxv];
    int n;
}ALGraph;
int visited[maxv]={0};

//初始化图(邻接矩阵)
MGraph InitMGraph(){
    MGraph mg;
    mg.n = 5;
    for(int i=0;i<mg.n;i++)
        for(int j=0;j<mg.n;j++)
            mg.edges[i][j] = 0;
    mg.edges[0][1] = 1;
    mg.edges[0][3] = 1;
    mg.edges[1][2] = 1;
    mg.edges[2][4] = 1;
    mg.edges[3][2] = 1;
    return mg;
}

//邻接矩阵转化为邻接表
void MaToList(MGraph mg,ALGraph *&alg)
{
    alg = (ALGraph *)malloc(sizeof(ALGraph));

    ArcNode *p;
    for(int k=0;k<mg.n;k++)
        alg->adjlist[k].firstarc = NULL;
    for(int i=0;i<mg.n;i++)
        for(int j=mg.n-1;j>=0;j--)
        {
            if (mg.edges[i][j]==1)
            {
                p = (ArcNode *)malloc(sizeof(ArcNode));
                p->adjvex = j;
                p->nextarc = alg->adjlist[i].firstarc;
                alg->adjlist[i].firstarc = p;
            }
        }
    alg->n = mg.n;
}

//DFS深度优先
void DFS(ALGraph *alg,int v)
{
    ArcNode *p;
    p = alg->adjlist[v].firstarc;
    visited[v] = 1;
    printf("%2d",v);
    while(p!=NULL)
    {
        if(visited[p->adjvex]==0)
            DFS(alg,p->adjvex);
        p = p->nextarc;
    }

}

//引入队列,广度优先
void BFS(ALGraph *alg,int v)
{
    int queue[maxv],rear =0,front = 0;
    int currentV;//当前顶点
    for(int i=0;i<maxv;i++)
        visited[i] = 0;
    rear = (rear+1)%maxv;
    queue[rear] = v;
    visited[v] = 1;
    printf("%2d",v);
    ArcNode *p;
    while(rear!=front)
    {
        front = (front+1)%maxv;
        currentV = queue[front];
        p = alg->adjlist[currentV].firstarc;
        while(p!=NULL)
        {
            if(visited[p->adjvex]==0)
            {
                visited[p->adjvex] = 1;
                rear = (rear+1)%maxv;
                queue[rear] = p->adjvex;
                printf("%2d",p->adjvex);
            }
            p = p->nextarc;
        }
    }
    printf("\n");
}
int main()
{   
    ALGraph *alg;
    alg = (ALGraph *)malloc(sizeof(ALGraph));
    MaToList(InitMGraph(),alg);
    DFS(alg,0);//从顶点0开始
    printf("\n");
    BFS(alg,0);
    return 0;
}
    原文作者:数据结构之图
    原文地址: https://blog.csdn.net/qq_34945661/article/details/73008301
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞