圖的深度優先搜尋(鄰接矩陣)
阿新 • • 發佈:2019-01-03
圖的遍歷(Traversing Graph)是指從圖中某一頂點出發訪問圖中其餘頂點,且使每個頂點僅被訪問一次。
深度優先搜尋(Depth First Search)
深度優先搜尋假設初始狀態下圖中所有頂點都未被訪問,嘗試優先搜尋從圖中某個頂點v出去,訪問此頂點,然後依次從v的未被訪問的鄰接點出發深度優先遍歷圖,直到圖中所有和v相連連的頂點都被訪問到。如果此時圖中還有沒有訪問到的頂點,則另選圖中未被訪問的某頂點作為起始點,重複上述過程,直到圖中所有頂點都被訪問到。具體實現如下:
#include <cstdio> #include <cstdlib> #define VERTEXNUM 100 //頂點個數 typedef char VertexType; //頂點型別 typedef int EdgeType; typedef enum{FALSE, TRUE} Boolean; Boolean visited[VERTEXNUM]; /********************************************** * * 鄰接矩陣儲存結構 * **********************************************/ typedef struct { VertexType vertexs[VERTEXNUM]; //頂點 EdgeType edges[VERTEXNUM][VERTEXNUM]; //鄰接矩陣 int vernum, edgenum; //圖中頂點和邊數 }Graph; /********************************************** * * 建立鄰接矩陣 * **********************************************/ void MakeGraph(Graph *graph) { int i, j, k; printf("請輸入頂點數和邊數:\n"); scanf("%d%d", &graph->vernum, &graph->edgenum); printf("請輸入頂點資訊(頂點號<CR>)每個頂點以回車作為結束:\n"); for(i = 0; i < graph->vernum; i++) { getchar(); scanf("%c", &graph->vertexs[i]); } for(i = 0; i < graph->vernum; i++) //初始化鄰接矩陣 { for(j = 0; j < graph->vernum; j++) { graph->edges[i][j] = 0; } } printf("請輸入每條邊對應的兩個頂點的序號(輸入格式為:i,j):\n"); for(k = 0; k < graph->edgenum; k++) { scanf("%d,%d", &i, &j); graph->edges[i - 1][j - 1] = 1; //(vi->vj)將edges[i][j]設定為1表示i,j間存在邊 } } /********************************************** * * 深度優先搜尋 * **********************************************/ void DFSTraverse(Graph *graph, int i) { printf("深度優先遍歷:頂點%c\n", graph->vertexs[i]); visited[i] = TRUE; for(int j = 0; j < graph->vernum; j++) { if(graph->edges[i][j] == 1 && !visited[j]) DFSTraverse(graph, j); } } void DFS(Graph *graph) { int i; for(i = 0; i < graph->vernum; i++) visited[i] = FALSE; for(i = 0; i < graph->vernum; i++) if(!visited[i]) DFSTraverse(graph, i); } int main() { Graph *graph = (Graph *)malloc(sizeof(Graph)); MakeGraph(graph); // 建立圖 DFS(graph); //深度優先搜尋 return 0; }
對於圖一中的圖,上述程式執行結果如圖二。
圖一
圖二
深度優先搜尋遍歷圖的時間複雜度為O(n^2),其中n為圖中頂點個數。