2024/12/4日工作总结

完成数据结构pta实验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 struct ArcNode{
    int adjvex;
    struct ArcNode* nextarc;
}ArcNode;

typedef struct VNode{
    int data;
    ArcNode *firstarc;
}VNode,AdjList[MVNum];

typedef struct {
    AdjList vertices;
    int vexnum,arcnum;
}ALGraph;

int LocateVex(ALGraph G,int v){
    for(int i = 0;i<G.vexnum;i++){
        if(G.vertices[i].data == v)
            return i;
    }
    return -1;
}

void CreateUDG(ALGraph &G){
    cin>>G.vexnum>>G.arcnum;
    for(int i=0;i<G.vexnum;i++){
        cin>>G.vertices[i].data;
        G.vertices[i].firstarc = NULL;
    }
    for(int k = 0;k<G.arcnum;k++){
        int v1,v2;
        cin>>v1>>v2;
        int i = LocateVex(G,v1);
        int j = LocateVex(G,v2);
        ArcNode* p1 = new ArcNode;
        p1->adjvex = j;
        p1->nextarc = G.vertices[i].firstarc;
        G.vertices[i].firstarc = p1;
        ArcNode* p2 = new ArcNode;
        p2->adjvex = i;
        p2->nextarc = G.vertices[j].firstarc;
        G.vertices[j].firstarc = p2;
    }
    
}

bool visited[MVNum] = {false};

void DFS_AL (ALGraph G,int v){
    if(v < 0 || v>=G.vexnum){
        cout<<"error"<<endl;
        return;
    }
    cout<<v<<' ';
    visited[v] = true;
    ArcNode *p = G.vertices[v].firstarc;
    while(p != NULL){
        int w = p->adjvex;
        if(!visited[w])
            DFS_AL(G,w);
        p=p->nextarc;
    }
}

int main(){
    ALGraph* G = new ALGraph;
    CreateUDG(*G);
    int v;
    cin>>v;
    DFS_AL(*G,LocateVex(*G,v));
    delete G;
    return 0;
}
posted @ 2024-12-18 11:16  vivi_vimi  阅读(15)  评论(0)    收藏  举报