无向图的邻接表表示法 及 深搜遍历DFS
昨天有小朋友求助关于图的邻接表示及深搜,记得一年前的我学数据结构也搞的乱七八糟的。我就顺便学下吧,网上的代码都好规范的感觉,读那些代码的能力不够,自己把那些代码简化了下。
非常感谢那些小朋友给我这么一次机会。
1 /* 无向图的邻接表表示 */ 2 3 #include <iostream> 4 #include <stdio.h> 5 #define N 50 6 using namespace std; 7 8 /************************************************************************/ 9 /* headNode: h_vex + firstnode 10 该头节点编号 后继结点(链)指针 11 Node: No + nextnode 12 头结点的下标 下一结点指针 13 Graph: vertices + vernum arcnum 14 表 结点数 边数 */ 15 /************************************************************************/ 16 17 struct Node { 18 int No; 19 Node *nextnode; 20 }; 21 22 struct headNode { 23 int h_vex; 24 Node *firstnode; 25 }; 26 27 struct Graph { 28 headNode vertices[N]; 29 int vexnum, arcnum; 30 }; 31 32 void createGraph (Graph *G) 33 { 34 scanf ("%d %d", &(*G).vexnum, &(*G).arcnum); //***************************INPUT 点数 边数 35 /* 初始化表头 */ 36 for (int i = 1;i <= (*G).vexnum;i ++) 37 { 38 (*G).vertices[i].h_vex = i; 39 (*G).vertices[i].firstnode = NULL; 40 } 41 /* 随着边的输入 把点一个个插进去 */ 42 for (int a, b, i = 1;i <= (*G).arcnum;i ++) 43 { 44 // an arc from (vertex)a to vertex(b) 45 scanf ("%d %d", &a, &b); //***************************INPUT 边信息 46 Node *tmp = new Node;// Node *tmp = (Node *)malloc(sizeof(Node)); 47 tmp->No = b; 48 tmp->nextnode = G->vertices[a].firstnode; 49 G->vertices[a].firstnode = tmp; 50 51 tmp = (Node *)malloc(sizeof(Node)); 52 tmp->No = a; 53 tmp->nextnode = G->vertices[b].firstnode; 54 G->vertices[b].firstnode = tmp; 55 } 56 } 57 58 void graphDFS (Graph G, int start, int *record) 59 { 60 Node *tmp = new Node; 61 record[start] = 1; // 经过记录为 1 62 printf ("%d->", start); 63 tmp = G.vertices[start].firstnode; 64 while (tmp != NULL) 65 { 66 if (!record[tmp->No]) 67 graphDFS (G, tmp->No,record); 68 printf ("\n"); // 粗略看递归层次 69 tmp = tmp->nextnode; 70 } 71 } 72 73 void travelGraph (Graph *G, int start) 74 { 75 /* 记录是否经过 */ 76 int done[N]; 77 // initial 78 for (int i = 1;i <= G->vexnum;i ++) 79 done[i] = 0; 80 81 /* 遍历 */ 82 graphDFS (*G, start, done); 83 84 /* 检验是否全部遍历 */ 85 for (int i = 0;i <= G->vexnum;i ++) 86 if (!done[i]) 87 printf ("cannot travel all the point --> %d", i); 88 } 89 90 int main () 91 { 92 //freopen ("in.txt", "r", stdin); 93 Graph *g = new Graph;// g = (Graph *)malloc(sizeof(Graph)); 94 createGraph (g); 95 96 /* Travel from Node x */ 97 int x; 98 scanf ("%d", &x); //******************************INPUT 开始遍历的位置 99 travelGraph (g, x); 100 } 101 102 /* 测试数据 103 6 7 104 1 6 105 1 5 106 1 2 107 3 6 108 4 3 109 4 2 110 3 2 111 3 112 113 114 */