各位大神能看一下我这个邻接表的深度优先遍历错在哪了吗,为什么运行不出来?
#include<stdio.h>
#include<stdlib.h>

#define MaxVnum 50

typedef char VertexType;
typedef struct ArcNode{
    int adjvex;
    double weight;
    struct ArcNode *nextarc;
}ArcNode;

typedef struct{ //头结点
    VertexType data;
    ArcNode *firstarc;
}AdjList[MaxVnum];

typedef struct{ // 图的类型定义
    int vexnum,arcnum; // 实际的顶点数、边数
    AdjList vertices;
}Graph;

int visited[MaxVnum];

void AddNode(Graph &G,int m,int n,float w){//表中添加n结点到m结点的路径
    ArcNode *p,*q,*s;
    p=(ArcNode*)malloc(sizeof(ArcNode));
    q=(ArcNode*)malloc(sizeof(ArcNode));
    s=(ArcNode*)malloc(sizeof(ArcNode));
    p->adjvex=n;
    p->nextarc=NULL;
    p->weight=w;
    q=G.vertices[m].firstarc;
    if(q==NULL){
        G.vertices[m].firstarc=p;//第一个节点为空直接添加
    }
    else{
        while(q->adjvex<p->adjvex){//不为空时,后移实现节点索引的递增排列
            s=q;
            q=q->nextarc;
            if(q==NULL){
                break;
            }
        }
        if(q==NULL){
            s->nextarc=p;
        }
        else{
            if(q==G.vertices[m].firstarc){
                s=G.vertices[m].firstarc;
                G.vertices[m].firstarc=p;
                p->nextarc=s;
            }
            else{
                s->nextarc=p;
                p->nextarc=q;
            }
        }
    }
}

void GreateGraph(Graph &G){
    int i,a,b;
    float c;
    printf("输入顶点数和边数:");
    scanf("%d %d",&G.vexnum,&G.arcnum);
    for(i=0;i<G.vexnum;i++){
        G.vertices[i].data=i;
    }
    printf("请输入邻接表:\n");
    for(i=0;i<G.arcnum;i++){
        scanf("%d%d%f",&a,&b,&c);
        AddNode(G,a,b,c);
    }
}  

void DFS(Graph G,int i){
    ArcNode *p;
    visited[i]=1;
    printf("%c",G.vertices[i].data);
    p=G.vertices[i].firstarc;
    while(p){
        if(!visited[p->adjvex]){
            DFS(G,p->adjvex);
        }
        p=p->nextarc;
    }   
}
void DFSTraverse(Graph G){
    int i;
    for(i=0;i<G.vexnum;i++){
        if(!visited[i]){
            DFS(G,i);   
        }
    }
}

int main(void){
    Graph G;
    int i,j;
    GreateGraph(G);
    printf("用邻接矩阵存储图的深度优先遍历:\n");
    DFSTraverse(G);
}
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐