用邻接矩阵存储无向图的深度优先遍历

实现代码:

#include<iostream>
#include<queue>
using namespace std;
//邻接矩阵存储无向图的深度优先遍历

#define MaxSize 10
#define inf 0x3f3f3f

bool book[MaxSize];
int n,m; //顶点数 边数

struct MGraph{ //定义图
    int edge[MaxSize][MaxSize]; //存储边
    int vexnum,arcnum; //定点数 边数
};

int FirstNeighbor(MGraph G,int x){

    for(int i=0;i<n;i++){
        if(G.edge[x][i]=1)
            return i;
    }

    return -1;
}

int NextNeighbor(MGraph G,int x,int j){

    for(int i=j+1;i<n;i++){
        if(G.edge[x][i]==1)
            return i;
    }

    return -1;
}

//深度优先遍历 
void dfs(MGraph G,int x){

    cout<<x<<" "; //访问队头元素
	book[x]=true;	
	
    for(int i=FirstNeighbor(G,x);i>=0;i=NextNeighbor(G,x,i)){
        if(book[i]==false){
            book[i]=true;
           	dfs(G,i);
        }
    }

}


int main(){

    cin>>n>>m; //输入顶点数和边数

    MGraph G; //定义一个图

    //初始化图
    G.vexnum=n; //顶点数
    G.arcnum=m; //边数
    for(int i=0;i<n;i++){
        for(int j=0;j<n;j++){
            if(i==j){
                G.edge[i][j]=0;
                G.edge[j][i]=0;
            }
            else{
                G.edge[i][j]=inf;
                G.edge[j][i]=inf;
            }

        }
    }


    //创建无向图
    for(int i=0;i<m;i++){
        int x,y; //起点 终点
        cin>>x>>y;
        G.edge[x][y]=1; //初始化边
        G.edge[y][x]=1;
    }

    //初始化标记数组
    for(int i=0;i<n;i++)
        book[i]=false;

    //当图不连通时,用for循环能遍历图的所有连通分量,求出图的所有连通分量的广度优先遍历
    for(int i=0;i<n;i++){
        if(book[i]==false)
            dfs(G,0); //深度优先遍历
    }

    return 0;
}

/*
输入样例:
5 5
0 1
0 2
0 4
1 3
2 4

输出样例
0 1 3 2 4
*/

运行结果:

在这里插入图片描述

  • 3
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值