1. 程式人生 > >用鄰接矩陣實現的深度優先遍歷和廣度優先遍歷

用鄰接矩陣實現的深度優先遍歷和廣度優先遍歷

using ++ while ext empty type push mat ron

  1 #include <stdio.h>
  2 #include <stdlib.h>
  3 #include <queue>
  4 #include <algorithm>
  5 using namespace std;
  6 
  7 #define ERROR -1
  8 #define MAXVEX 100      
  9 
 10 typedef int VertexType;
 11 typedef int VRType;
 12 typedef int EdgeType;
 13 bool visited[MAXVEX];    //
訪問標誌數組 14 15 typedef struct ArcCell 16 { 17 VRType adj; 18 }ArcCell, AdjMatrix[MAXVEX][MAXVEX]; 19 20 typedef struct 21 { 22 VertexType vexs[MAXVEX]; //頂點向量 23 AdjMatrix arcs; //鄰接矩陣 24 int vexnum; //頂點數 25 int arcnum; //邊數 26 }MGraph; 27 28
/********* 按照頂點的信息找下表 ********/ 29 int LocateVex(MGraph G, int v){ 30 int i; 31 for (i = 0; i < G.vexnum; ++i){ 32 if (G.vexs[i] == v) //找到相匹配的 33 break; 34 } 35 if (i<G.vexnum) //如果存在就返回該下標 36 return i; 37 else 38 return
ERROR; //否則返回錯誤 39 } 40 41 /********* 進行深搜 *********/ 42 void DFS(MGraph G, int i) 43 { 44 int j; 45 visited[i] = true; //標記為訪問過 46 printf("%d ", G.vexs[i]); //打印出該頂點的名字 47 for (j = 0; j<G.vexnum; j++) 48 if (G.arcs[i][j].adj == 1 && !visited[j]) 49 DFS(G, j); 50 } 51 52 /********* 開始對圖進行遍歷 *********/ 53 void DFSTraverse(MGraph G) 54 { 55 int i; 56 for (i = 0; i<G.vexnum; i++) 57 visited[i] = false; 58 for (i = 0; i<G.vexnum; i++) 59 if (!visited[i]) 60 DFS(G, i); 61 } 62 63 /********* 建圖 *********/ 64 void SetGraph(MGraph &G){ 65 printf("請輸入圖的頂點數目: "); 66 scanf("%d", &G.vexnum); 67 for (int i = 0; i<G.vexnum; ++i) 68 { 69 printf("請輸入第%d個頂點信息:", i + 1); 70 scanf("%d", &G.vexs[i]); 71 } 72 printf("請輸入圖的邊的數目: "); 73 scanf("%d", &G.arcnum); 74 //將矩陣進行初始化 75 for (int i = 0; i < G.vexnum; i++){ 76 for (int j = 0; j < G.vexnum; j++){ 77 G.arcs[i][j].adj = 0; 78 } 79 } 80 printf("輸入格式為“頂點a 頂點b”\n"); 81 for (int k = 0; k < G.arcnum; ++k) 82 { 83 int v1, v2, m, n; 84 printf("請輸入第 %d 條邊的起始點和終端點: ", k + 1); 85 scanf("%d%d", &v1, &v2); 86 m = LocateVex(G, v1); //找出所對應的下標 87 n = LocateVex(G, v2); 88 if (m >= 0 && n >= 0) //滿足情況的話 89 { 90 G.arcs[m][n].adj = 1; //n--m 之間存在邊 91 G.arcs[n][m].adj = 1; 92 } 93 else 94 printf("輸入錯誤!\n"); 95 } 96 } 97 98 /******** 廣搜 ********/ 99 void BFS(MGraph G, int i){ 100 queue<int>q; 101 while (!q.empty()){ 102 q.pop(); 103 } 104 q.push(i); 105 while (!q.empty()){ 106 int u = q.front(); 107 q.pop(); 108 if (visited[u]) 109 continue; 110 printf("%d ", G.vexs[u]); 111 visited[u] = true; 112 for (int j = 0; j < G.vexnum; j++){ 113 if (G.arcs[i][j].adj == 1 && !visited[j]) 114 q.push(j); 115 } 116 } 117 } 118 119 /******** 進行廣搜 *******/ 120 void BFSTraverse(MGraph G){ 121 for (int i = 0; i < G.vexnum; i++){ 122 visited[i] = false; 123 } 124 for (int i = 0; i<G.vexnum; i++) 125 if (!visited[i]) 126 BFS(G, i); 127 } 128 129 int main() 130 { 131 MGraph G; 132 SetGraph(G); 133 DFSTraverse(G); 134 printf("\n\n\n\n"); 135 BFSTraverse(G); 136 printf("\n"); 137 return 0; 138 }

用鄰接矩陣實現的深度優先遍歷和廣度優先遍歷