标签:输入 *** break front ace bool 标记 之间 nbsp
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 }
标签:输入 *** break front ace bool 标记 之间 nbsp
原文地址:http://www.cnblogs.com/jaydenouyang/p/7798409.html