1 #include2 #include 3 4 #include 5 #define Max 20 6 using namespace std; 7 8 class Vertex 9 { 10 public: 11 Vertex(char lab) 12 { 13 Label=lab; 14 wasVisited=false; 15 } 16 public: 17 bool wasVisited; 18 char Label; 19 }; 20 21 22 class Graph 23 { 24 25 public: 26 Graph();//构造函数 27 ~Graph();//析构函数 28 void addVertex(char lab);//增加一个节点 29 void addEdge(int start,int end);//增加一条边,起点到终点 30 void printMatrix();//打印出矩阵 31 void showVertex(int v); 32 void DFS(); 33 void BFS(); 34 private: 35 Vertex* vertexList[Max]; //存放每个节点的指针的数组 36 int nVerts;//实际数量 37 int adjMat[Max][Max];//矩阵 38 int getAdjUnvisitedVertex(int v);//获得其相邻的节点 在邻接矩阵里找其最近的 39 }; 40 41 void Graph::DFS() 42 { 43 stack gStack; 44 vertexList[0]->wasVisited=true; 45 showVertex(0); 46 gStack.push(0); 47 int v; 48 while(gStack.size()>0) 49 { 50 v=getAdjUnvisitedVertex(gStack.top()); 51 if(v==-1) 52 { 53 cout<<"出:"< < wasVisited=true; 59 showVertex(v); 60 gStack.push(v); 61 } 62 63 } 64 65 for(int j=0;j wasVisited=false; 67 68 69 } 70 void Graph::BFS() 71 { 72 queue gQueue; 73 vertexList[0]->wasVisited=true; 74 showVertex(0); 75 gQueue.push(0); 76 int vert1,vert2; 77 while(gQueue.size()>0) 78 { 79 vert1=gQueue.front(); 80 gQueue.pop(); 81 vert2=getAdjUnvisitedVertex(vert1); 82 while(vert2!=-1) 83 { 84 vertexList[vert2]->wasVisited=true; 85 showVertex(vert2); 86 gQueue.push(vert2); 87 vert2=getAdjUnvisitedVertex(vert1); 88 } 89 } 90 cout< wasVisited=false; 93 94 95 } 96 97 int Graph::getAdjUnvisitedVertex(int v)//得到其相邻节点 98 { 99 for(int j=0;j wasVisited==false))//找其第一个相邻(邻接)的且没有被访问过的102 return j;103 }104 105 return -1;106 107 }108 void Graph::showVertex(int v) //展示该下标对应的节点109 {110 cout< Label<<" ";111 }112 Graph::Graph()113 {114 115 nVerts=0;116 for(int i=0;i