数据结构实验7

7-1 邻接表存储实现图的深度优先遍历
编写程序,实现由邻接表存储实现无向图的深度优先搜索遍历的功能。顶点为字符型。

输入格式:
第一行输入顶点个数及边的个数,第二行依次输入各顶点,第三行开始依次输入边的两个顶点,用空格分开。最后输入深度优先遍历的起始点。

输出格式:
输出深度优先遍历结果,空格分开,若起始点不合理,则输出error。

输入样例:
在这里给出一组输入。例如:

8 9
0 1 2 3 4 5 6 7
0 1
0 2
1 3
1 4
2 5
2 6
3 7
4 7
5 6
0
输出样例:
在这里给出相应的输出。例如:

0 2 6 5 1 4 7 3

#include<iostream>
using namespace std;
#define MVNum 100
typedef char OtherInfo;
int visited[MVNum]={0};
typedef struct ArcNode{
    int adjvex;
    OtherInfo info;
    struct ArcNode* next;
}ArcNode;
typedef struct VNode{
    char vex;
    ArcNode* first;
}VNode,AdjList[MVNum];
typedef struct{
    AdjList vertices;
    int vexnum,arcnum;
}ALGraph;
int LocateVex(ALGraph G,char v){
    for(int i=0;i<G.vexnum;++i){
        if(G.vertices[i].vex==v)return i;
    }
    return -1;
}
void CreatALGraph(ALGraph &G,int &err){
    cin>>G.vexnum>>G.arcnum;
    for(int i=0;i<G.vexnum;++i){
        cin>>G.vertices[i].vex;
        G.vertices[i].first=NULL;
    }
    for(int k=0;k<G.arcnum;++k){
        char v1,v2;
        cin>>v1>>v2;
    int i,j;
    i=LocateVex(G,v1);j=LocateVex(G,v2);
    if(i==-1||j==-1)err=1;
    else{
        ArcNode * p1=new ArcNode;
        p1->adjvex=j;
        p1->next=G.vertices[i].first;
        G.vertices[i].first=p1;
        ArcNode * p2=new ArcNode;
        p2->adjvex=i;
        p2->next=G.vertices[j].first;
        G.vertices[j].first=p2;
    }
    }
}
void DFS_ALGraph(ALGraph G,int adj){
    cout<<G.vertices[adj].vex<<" ";
    visited[adj]=1;
    ArcNode* p=G.vertices[adj].first;
    while(p!=NULL){
        if(visited[p->adjvex]!=1)DFS_ALGraph(G,p->adjvex);
        p=p->next;
    }
}

int main(){
    ALGraph G;
    int err=0;
    char star;
    CreatALGraph(G,err);
    cin>>star;
    int adj=LocateVex(G,star);
    if(adj==-1||err==1) cout<<"error";
    else{
        DFS_ALGraph(G,adj);
    }
    return 0;
}
posted @   呓语-MSHK  阅读(2)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 一文读懂知识蒸馏
· 终于写完轮子一部分:tcp代理 了,记录一下
点击右上角即可分享
微信分享提示