參考博客:圖的深度優先遍歷(遞歸、非遞歸;鄰接表,鄰接矩陣)
本篇默認連通圖,非連通情況會在鄰接表處補上
1.鄰接矩陣的遞歸解法
#include<stdio.h> #define MAX 100 typedef struct { int e[MAX][MAX]; int ves; int edge; int book[MAX];//標志判斷是否有被訪問過 }MGraph; void createMGraph(MGraph *G) { int i; int j; int start; int end; printf("please input the ves and edge:\n"); scanf("%d %d",&G->ves,&G->edge); //初始化 for(i = 0; i < G->ves; i++) { for(j = 0; j < G->ves; j++) G->e[i][j] = 0; G->book[i] = 0;//沒被訪問過的結點置為0 } //創建鄰接矩陣 printf("please input the (vi,vj)\n"); for(i = 0; i < G->edge; i++) { scanf("%d %d",&start,&end); G->e[start][end] = 1; } } void dfs(MGraph *G,int ves) { int i; G->book[ves] = 1;//被訪問過的結點置為1 printf("%d ",ves); for(i = 0; i < G->ves; i++) if(G->e[ves][i] != 0 && G->book[i] == 0) dfs(G,i); } int main() { MGraph G; createMGraph(&G); dfs(&G,0); return 0; } /* 輸入樣例: 8 18 0 1 0 2 1 0 1 3 1 4 2 0 2 5 2 6 3 1 3 7 4 1 4 7 5 2 5 6 6 2 6 5 7 3 7 4 */
2.鄰接矩陣的非遞歸解法
基本思想:
- 初始化棧
- 輸出起始頂點,起始頂點改為“已訪問”標志,將起始頂點進棧
- 重復以下操作直至棧空:
- 去棧頂元素頂點,找到未被訪問的鄰接結點W
- 輸出W,W改為“已訪問”,將W進棧
- 否則當前頂點退棧
#include<stdio.h> #include<stack> #define MAX 100 using namespace std; typedef struct { int e[MAX][MAX]; int ves; int edge; int book[MAX];//標志判斷是否有被訪問過 }MGraph; void createMGraph(MGraph *G) { int i; int j; int start; int end; printf("please input the ves and edge:\n"); scanf("%d %d",&G->ves,&G->edge); //初始化 for(i = 0; i < G->ves; i++) { for(j = 0; j < G->ves; j++) G->e[i][j] = 0; G->book[i] = 0;//沒被訪問過的結點置為0 } //創建鄰接矩陣 printf("please input the (vi,vj)\n"); for(i = 0; i < G->edge; i++) { scanf("%d %d",&start,&end); G->e[start][end] = 1; } } void dfs(MGraph* G,int ves) { stack<int> s;//創建一個棧 printf("%d ", ves); G->book[ves] = 1;//已經訪問過結點ves了 s.push(ves);//入棧 while(!s.empty()) { int data, i; data = s.top();//取top的頂點 for(i = 0; i < G->ves; i++) { if(G->e[data][i] != 0 && G->book[i] != 1) { printf("%d ", i); G->book[i] = 1; s.push(i); break;//深度優先 } } if(i == G->ves)//data相鄰的結點都訪問結束了,就彈出data { s.pop(); } } } int main() { MGraph G; createMGraph(&G); dfs(&G,0); return 0; } /* 輸入樣例: 8 18 0 1 0 2 1 0 1 3 1 4 2 0 2 5 2 6 3 1 3 7 4 1 4 7 5 2 5 6 6 2 6 5 7 3 7 4 */