深度优先生成树

23 篇文章 0 订阅

Problem Description

设有一连通无向图,其顶点值为字符型并假设各值互不相等,采用邻接矩阵表示法存储表示。利用DFS算法求其深度优先生成树(从下标0的顶点开始遍历),并在遍历过程中输出深度优先生成树的每一条边。

 Input

有多组测试数据,每组数据的第一行为两个整数n和e,表示n个顶点和e条边(0<n<20);第二行为其n个顶点的值,按输入顺序进行存储;后面有e行,表示e条边的信息,每条边信息占一行,包括边所依附的顶点下标i和j,数据之间用空格隔开。

 Output

输出深度优先生成树的每一条边,每条边信息之后均有一空格,每组输出占一行,具体格式见样例。

 Sample Input

4 4
ABCD
0 1
0 3
1 2
1 3

 Sample Output

(A,B) (B,C) (B,D) 
#include <iostream>
#include <stdlib.h>
#define maxvex 20
#include<stdio.h>
using namespace std;

typedef struct {
    int adjvex;

} ArcCell,ArcCells[maxvex][maxvex];

typedef struct {
    char vertex[maxvex];
    ArcCells arcs;
    int arcnum,vexnum;

} MatrixGraph;





void CreatUDM(MatrixGraph &G,int n,int e) {

    G.arcnum=e;
    G.vexnum=n;
    for(int i=0; i<G.vexnum; i++) {
        cin>>G.vertex[i];

        for(int j=0; j<G.vexnum; j++) {
            G.arcs[i][j].adjvex=0;

        }
    }



    for(int i=0; i<G.arcnum; i++) {
        int a,b;
        cin>>a>>b;
        G.arcs[a][b].adjvex=1;
       G.arcs[b][a].adjvex=1;
    }

}








bool vistited[maxvex];

void InitVistied() {

    for(int i=0; i<maxvex; i++) {
        vistited[i]=false;
    }
}



void MatrixDFSTraverse(MatrixGraph G,int v) {
    vistited[v]=true;
   // cout<<G.vertex[v];

    for(int i=0; i<G.vexnum; i++) {
        if(!vistited[i]&&G.arcs[v][i].adjvex!=0) {
                cout<<"("<<G.vertex[v]<<","<<G.vertex[i]<<")"<<" ";
            MatrixDFSTraverse(G,i);
        }
    }


}

int main() {
  
    int n,e;

    while(cin>>n>>e) {
       MatrixGraph g;
      CreatUDM(g,n,e);
      InitVistied();
     MatrixDFSTraverse(g,0);
cout<<endl;
    }
    return 0;
}




 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

haibianyoushark

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值