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
| #include <iostream> using namespace std;
const int MaxSize = 10; int visited[MaxSize] = { 0 };
template <class DataType> class MGraph { public: MGraph(DataType a[], int n, int e); ~MGraph() {}; void DFTraverse(int v); void BFTraverse(int v); private: DataType vertex[MaxSize]; int edge[MaxSize][MaxSize]; int vertexNum, edgeNum; };
template <class DataType> MGraph<DataType>::MGraph(DataType a[], int n, int e) { int i, j, k; vertexNum = n; edgeNum = e; for (i = 0; i < vertexNum; i++) vertex[i] = a[i]; for (i = 0; i < vertexNum; i++) for (j = 0; j < vertexNum; j++) edge[i][j] = 0; for (k = 0; k < edgeNum; k++) { cout << "请输入边依附的两个顶点的编号:"; cin >> i >> j; edge[i][j] = 1; edge[j][i] = 1; } }
template <class DataType> void MGraph<DataType>::DFTraverse(int v) { cout << vertex[v]; visited[v] = 1; for (int j = 0; j < vertexNum; j++) if (edge[v][j] == 1 && visited[j] == 0) DFTraverse(j); }
template <class DataType> void MGraph<DataType>::BFTraverse(int v) { int w, j, Q[MaxSize]; int front = -1, rear = -1; cout << vertex[v]; visited[v] = 1; Q[++rear] = v; while (front != rear) { w = Q[++front]; for (j = 0; j < vertexNum; j++) if (edge[w][j] == 1 && visited[j] == 0) { cout << vertex[j]; visited[j] = 1; Q[++rear] = j; } } }
int main() { int i; string ch[] = { "V1","V2","V3","V4","V5" }; MGraph<string> MG{ ch, 5, 6 }; for (i = 0; i < MaxSize; i++) visited[i] = 0; cout << "\n深度优先遍历序列是:" << endl; MG.DFTraverse(0); for (i = 0; i < MaxSize; i++) visited[i] = 0; cout << "\n广度优先遍历序列是:" << endl; MG.BFTraverse(0); return 0; }
|