鄰接矩陣實現圖的深度優先搜尋(2)

來源:互聯網
上載者:User

標籤:

/*樹的鄰接矩陣的儲存結構*/#include <stdio.h>#include <stdlib.h>#define MAXVEX      10#define InitEdge    0typedef char VertexType;typedef int EdgeType;typedef struct MGraph{    VertexType vex[MAXVEX];    EdgeType arc[MAXVEX][MAXVEX];    int numVertexes;    int numEdges;}MGraph;static int Flag[MAXVEX];void CreateMGraph(MGraph *G){    int i = 0,j = 0,k = 0,w = 0,m = 0,n = 0;    char c;    printf("請輸入頂點數和邊數,之間用逗號隔開 :\n");    fflush(stdin);    scanf("%d,%d",&(G->numVertexes),&(G->numEdges));    printf("請輸入頂點的值 :\n");    fflush(stdin);    scanf("%c",&c);    while(i < G->numVertexes)    {        if(c == ‘\n‘)            break;        G->vex[i++] = c;        scanf("%c",&c);    }    //鄰接矩陣的初始化    for(i = 0;i < G->numVertexes;i++)                                   //鄰接矩陣的初始化,初始化為0    {        for(j = 0;j < G->numVertexes;j++)        {            G->arc[i][j] = InitEdge;        }    }    for(i = 0;i < G->numVertexes;i++)                                   //標識數組的初始化,0表示未訪問過    {        Flag[i] = 0;    }    fflush(stdin);    for(m = 0,n = 0,k = 0; k < G->numEdges; k++)    {        printf("請輸入邊(Vi~Vj)的頂點下標i和j,以及權重w:\n");        scanf("%d,%d,%d",&m,&n,&w);        G->arc[m][n] = w;        G->arc[n][m] = G->arc[m][n];    }    printf("\n\n結點中存放的資料為 :\n");    for(i = 0;i < G->numVertexes;i++)    {        printf("%c ",G->vex[i]);    }    printf("\n\n您輸入的鄰接矩陣為:\n");    for(i = 0;i < G->numVertexes;i++)                                 //輸出鄰接矩陣方便查看輸入是否有誤    {        for(j = 0;j < G->numVertexes;j++)        {            printf("%d ",G->arc[i][j]);        }        printf("\n");    }    printf("\n\n標示數組的值初始化為 :\n");    for(i = 0;i < G->numVertexes;i++)    {        printf("%d ",Flag[i]);    }}void DepthFirstSearch(MGraph *G,int i){    int j = 0;    if(Flag[i] == 0)    {        printf("%c ",G->vex[i]);    }    Flag[i] = 1;    for(j = 0;j < G->numVertexes;j++)    {        if((G->arc[i][j]) != InitEdge && 0 == (Flag[j]))        {            DepthFirstSearch(G,j);        }    }}int main(){    int k = 0;                                      //設定從鄰接矩陣的第幾行開始DFS搜尋,這裡從第1行開始    struct MGraph *G;    CreateMGraph(G);    printf("\n**********************************************\n");    printf("DFS的排序結果為: \n");    DepthFirstSearch(G,k);    printf("\n**********************************************\n");    return 0;}

  

鄰接矩陣實現圖的深度優先搜尋(2)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.