#include <iostream> #include "malloc.h" #include "stdlib.h" using namespace std; typedef bool* pbool; template<class T> class Graph { public: Graph(int vertexNum,int adjNum); virtual ~Graph(); T* vertex; bool** adjArr; int vertexNum; int adjNum; void DFSTravse(); void DFS(int i,bool *flag); //void BFSTravse(); //void BFS(); protected: private: }; template<class T> Graph<T>::Graph(int vertexNum,int adjNum):vertexNum(vertexNum),adjNum(adjNum) { vertex = new T[vertexNum]; adjArr = new pbool[vertexNum]; for(int i=0;i<vertexNum;i++) { adjArr[i] = new bool[vertexNum]; } } template<class T> Graph<T>::~Graph() { delete [] vertex; for(int i=0;i<vertexNum;i++) { delete[] adjArr[i]; } delete[] adjArr; } template<class T> void Graph<T>::DFSTravse() { bool* flag = new bool[vertexNum]; //initialize flag for(int i=0;i<vertexNum;i++) { flag[i] = false; } for(int i=0;i<vertexNum;i++) { if(!flag[i]) { this->DFS(i,flag); } } delete[] flag; } template<class T> void Graph<T>::DFS(int i,bool* flag) { cout<<vertex[i]<<endl; flag[i] = true; for(int j=0;j<vertexNum;j++) { if(adjArr[i][j]&&!flag[j]) { DFS(j,flag); } } } int main() { int vertexNum,adjNum; cout<<"input vertextNum and adjNum"<<endl; cin>>vertexNum>>adjNum; Graph<char> * graph = new Graph<char>(vertexNum,adjNum); for(int i=0;i<vertexNum;i++) { cin>>graph->vertex[i]; } system("pause"); for(int i=0;i<adjNum;i++) { int x,y; cin>>x>>y; cin>>graph->adjArr[x][y]; graph->adjArr[y][x] = graph->adjArr[x][y]; } system("pause"); graph->DFSTravse(); system("pause"); return 0; }
时间: 2024-10-17 22:25:20