圖的鄰接表存儲與訪問

#define MAX_VERTEXT_NUM 20

typedef struct edge{     /*邊定義*/
    int from,to,weight;
}Edge,*Edged;

typedef struct ArcNode{     /*邊結點定義*/
    int adjvex;
    struct ArcNode *nextArc;
    int weight;
}ArcNode;

typedef struct VNode{     /*頂點定義*/
    char data;
    ArcNode *firstArc;
}VNode, AdjList[MAX_VERTEXT_NUM];

typedef struct{     /*圖定義*/
    AdjList verTices;
    int vexNum;
    int arcNum;
    int kind;
    indegree Indegree;
}ALGraph;

/*建立有向圖G 的鄰接表存儲*/
void CreateGraph(ALGraph *G)
{
    int i,j,k,weight;
    ArcNode *arcNode;
    printf("請輸入頂點數和邊數:");
    scanf("%d %d",&G->vexNum,&G->arcNum);
    //建立頂點表
    for (i = 0; i < G->vexNum; i++)
    {
        printf_s("請輸入第%d個頂點:", i);
        cin>>G->verTices[i].data;
        arcNode = (ArcNode *)malloc(sizeof(ArcNode));
        arcNode->adjvex=NULL;
        arcNode->nextArc=NULL;
        G->verTices[i].firstArc=arcNode;
    }
    //建立邊表
    for (k = 0; k < G->arcNum; k++)
    {
        printf("請輸入(vi-vj)的頂點對序號");
        scanf("%d %d",&i,&j);
        arcNode = (ArcNode *)malloc(sizeof(ArcNode));
        arcNode->adjvex = j;
        arcNode->nextArc = G->verTices[i].firstArc->nextArc;//插入表頭
        G->verTices[i].firstArc ->nextArc= arcNode;
    }
}

//深度優先周遊
void DFSM(ALGraph *G,int i){
    ArcNode *p;
    cout<<G->verTices[i].data;
    mark[i]=TRUE;
    p=G->verTices[i].firstArc;
    while(p){
        if(mark[p->adjvex]==FALSE)
            DFSM(G,p->adjvex);
        p=p->nextArc;       
    }
}

void DFS(ALGraph *G){
    for ( int i=0; i<G->vexNum;i++)
        mark[i]=FALSE;
    for( int i=0; i<G->vexNum;i++)
        if(!mark[i])
            DFSM(G,i);
}

//廣度優先周遊
void BFS(ALGraph *G,int x){
    ArcNode *p;
    int w;
    using std::queue;
    queue<int> Q;
    for ( int i=0; i<G->vexNum;i++) {mark[i]=FALSE;}
    cout<<G->verTices[x].data;
    mark[x]=TRUE;
    Q.push(x);
    while(!Q.empty()){
        int v=Q.front();
        Q.pop();
        p=G->verTices[v].firstArc;
        while(p){
            int w=p->adjvex;
            if(mark[w]==FALSE){
                mark[w]=TRUE;
                cout<<G->verTices[w].data;
                Q.push(w);}
            p=p->nextArc;
            }
        }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章