MGraph.h
#ifndef __MGRAPH_H__ #define __MGRAPH_H__ const int MaxSize = 10; template <class T> class MGraph { public: MGraph(T _maxtrix[], int _vertex, int _edge); ~MGraph(); public: void DFSTraverse(int _vertex); void BFSTraverse(int _vertex); private: T verMat[MaxSize]; int edgeMat[MaxSize][MaxSize]; int verNum, edgeNum; }; #endif
MGraph.cpp
#include "MGraph.h" #include <iostream> using namespace std; template <class T> MGraph<T>::MGraph(T _maxtrix[], int _vertex, int _edge) { verNum = _vertex; edgeNum = _edge; for (int i = 0; i < verNum; i++) verMat[i] = _maxtrix[i]; for (int i = 0; i < verNum; i++) for (int j = 0; j < verNum; j++) edgeMat[i][j] = 0; for (int k = 0; k < edgeNum; k++) { int i = 0, j = 0; cin >> i >> j; edgeMat[i][j] = 1; edgeMat[j][i] = 1; } } template <class T> MGraph<T>::~MGraph() {} template <class T> void MGraph<T>::DFSTraverse(int _vertex) { static int * visited = new int[verNum]; cout << verMat[_vertex]; visited[_vertex] = 1; for (int i = 0; i < verNum; i++) if (edgeMat[_vertex][i] == 1 && visited[i] != 1) DFSTraverse(i); } template <class T> void MGraph<T>::BFSTraverse(int _vertex) { int front = -1, rear = -1; static int * visited = new int[verNum]; T *queue = new T[verNum]; cout << verMat[_vertex]; visited[_vertex] = 1; queue[++rear] = _vertex; while (front != rear) { _vertex = queue[++front]; for(int i = 0; i<verNum; i++) if (edgeMat[_vertex][i] == 1 && visited[i] != 1) { cout << verMat[i]; visited[i] = 1; queue[++rear] = i; } } }
AdjacencyMatrix.cpp
#include <iostream> #include "MGraph.h" #include "MGraph.cpp" using namespace std; int main() { int verMat[4] = { 0, 1, 2, 3 }; MGraph<int> G(verMat, 4, 4); G.BFSTraverse(0); cout << endl; G.DFSTraverse(0); cout << endl; return 0; }
输入输出
//输入 0 1 0 3 1 3 1 2 即组成无向图: 其邻接矩阵为 0———3 | 0 1 2 3 | / ——————————————— | / 0| 0 1 0 1 1———2 1| 1 0 1 1 2| 0 1 0 0 3| 1 1 0 0 //输出 0132 0123