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>
#include<cstdio>
using namespace std;
struct edge{
    int v;
    edge* next;
};
struct node{
    char val;
    edge* next;
}a[1010];
int n;

int find(char ch){
    for(int i=0;i<n;i++){
        if(a[i].val==ch){
            return i;
        }
    }
    return -1;
}

void add(int u,int v){
    edge* e=new edge();
    e->next=a[u].next;
    e->v=v;
    a[u].next=e;
}

bool st[1010];
void dfs(int u){
    cout<<a[u].val<<' ';
    st[u]=1;
    edge* e=a[u].next;
    while(e!=NULL){
        if(st[e->v]==0){
            dfs(e->v);
        }
        e=e->next;
    }
}

int main(){
    int m;
    cin>>n>>m;
    
    for(int i=0;i<n;i++){
        char ch;
        cin>>ch;
        a[i].val=ch;
    }
    
    for(int i=0;i<m;i++){
        char u,v;
        cin>>u>>v;
        int uu=find(u),vv=find(v);
        add(uu,vv);
        add(vv,uu);
    }
    
    char ch;
    cin>>ch;
    int k;
    if((k=find(ch))!=-1){
        dfs(k);
    }else{
        cout<<"error";
    }
    
    return 0;
}

  

posted @ 2021-12-08 23:20  好(justice)……  阅读(213)  评论(0编辑  收藏  举报