第十一週——項目二—操作用鄰接表存儲的圖

/*                
 * Copyright (c) 2017,煙臺大學計算機學院            
 * All right reserved.                
 * 文件名稱:graph      
 * 作者:尹娜               
 * 完成日期:2017年11月14日                
 * 版本號:v1.0               
 *                
 * 問題描述: 操作用鄰接表存儲的圖
 * 輸入描述:標準函數輸入                
 * 程序輸出:頂點的出度       
*/      

提示:(1)分別設計函數實現算法;(2)不要全部實現完再測試,而是實現一個,測試一個;(3)請利用圖算法庫

#include <stdio.h>
#include <malloc.h>
#include "graph.h"

//返回圖G中編號爲v的頂點的出度
int OutDegree(ALGraph *G,int v)
{
    ArcNode *p;
    int n=0;
    p=G->adjlist[v].firstarc;
    while (p!=NULL)
    {
        n++;
        p=p->nextarc;
    }
    return n;
}

//輸出圖G中每個頂點的出度
void OutDs(ALGraph *G)
{
    int i;
    for (i=0; i<G->n; i++)
        printf("  頂點%d:%d\n",i,OutDegree(G,i));
}

//輸出圖G中出度最大的一個頂點
void OutMaxDs(ALGraph *G)
{
    int maxv=0,maxds=0,i,x;
    for (i=0; i<G->n; i++)
    {
        x=OutDegree(G,i);
        if (x>maxds)
        {
            maxds=x;
            maxv=i;
        }
    }
    printf("頂點%d,出度=%d\n",maxv,maxds);
}
//輸出圖G中出度爲0的頂點數
void ZeroDs(ALGraph *G)
{
    int i,x;
    for (i=0; i<G->n; i++)
    {
        x=OutDegree(G,i);
        if (x==0)
            printf("%2d",i);
    }
    printf("\n");
}

//返回圖G中是否存在邊<i,j>
bool Arc(ALGraph *G, int i,int j)
{
    ArcNode *p;
    bool found = false;
    p=G->adjlist[i].firstarc;
    while (p!=NULL)
    {
        if(p->adjvex==j)
        {
            found = true;
            break;
        }
        p=p->nextarc;
    }
    return found;
}

int main()
{
    ALGraph *G;
    int A[7][7]=
    {
        {0,1,1,1,0,0,0},
        {0,0,0,0,1,0,0},
        {0,0,0,0,1,1,0},
        {0,0,0,0,0,0,1},
        {0,0,0,0,0,0,0},
        {0,0,0,1,1,0,1},
        {0,1,0,0,0,0,0}
    };
    ArrayToList(A[0], 7, G);
    printf("(1)各頂點出度:\n");
    OutDs(G);
    printf("(2)最大出度的頂點信息:");
    OutMaxDs(G);
    printf("(3)出度爲0的頂點:");
    ZeroDs(G);
    printf("(4)邊<2,6>存在嗎?");
    if(Arc(G,2,6))
        printf("是\n");
    else
        printf("否\n");
    printf("\n");
    return 0;
}
運行結果:



發佈了62 篇原創文章 · 獲贊 3 · 訪問量 8308
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章