1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124
| #include <iostream> #define MaxV 10010 #define INF INT_MAX
using namespace std;
typedef string infoType;
typedef struct ANode { int adjvex; struct ANode* nextarc; int weight; } ArcNode;
typedef struct { infoType info; ArcNode* firstarc; } VNode;
typedef struct { VNode adjlist[MaxV]; int n, e; } AdjGraph;
int qu[MaxV]; bool visted[MaxV];
void CreateAdj(AdjGraph*& G,int A[MaxV][MaxV], int n, int e) { ArcNode *p; G = (AdjGraph*)malloc(sizeof(AdjGraph)); for (int i = 0; i < n; ++i) G->adjlist[i].firstarc = NULL; for (int i = 0; i < n; ++i) { for (int j = n-1; j >= 0; --j) { if (A[i][j] != 0 && A[i][j] != INF) { p = (ArcNode*)malloc(sizeof(ArcNode)); p->adjvex = j; p->weight = A[i][j]; p->nextarc = G->adjlist[i].firstarc; G->adjlist[i].firstarc = p; } } } G->n = n; G->e = e; }
void DispAdj(AdjGraph* G) { ArcNode* p; for (int i = 0; i < G->n; ++i) { p = G->adjlist[i].firstarc; cout << i << " :"; while (p != NULL) { cout << p->adjvex << "[" << p->weight << "]->"; p = p->nextarc; } cout << endl; } }
void DestroyAdj(AdjGraph*& G) { ArcNode* pre, *p; for (int i = 0; i < G->n; ++i) { pre = G->adjlist[i].firstarc; if (pre != NULL) { p = pre->nextarc; while (p != NULL) { free(pre); pre = p; p=p->nextarc; } free(pre); } } free(G); }
void bfs(AdjGraph* G, int v) { ArcNode* p; memset(qu, -1, sizeof(qu)); int rear = -1, front = -1; rear++; qu[rear] = v; visted[v] = true; while (front != rear) { int i = qu[front+1]; front++; cout << i << " -> "; p = G->adjlist[i].firstarc; while (p != NULL) { if (!visted[p->adjvex]) { rear++; qu[rear] = p->adjvex; visted[p->adjvex] = true; } p = p->nextarc; } } cout << endl; }
int main () { int A[][MaxV] = { {0,2,1}, {2,0,3}, {1,3,0} }; AdjGraph* G; CreateAdj(G, A, 3, 3); DispAdj(G); bfs(G, 1); DestroyAdj(G); }
|