C++資料結構 21 圖-鄰接矩陣
阿新 • • 發佈:2018-11-24
#include <iostream> #define MAX_VERTS 20 using namespace std; /**使用鄰接矩陣來表示一個圖**/ class Vertex { public: Vertex(char lab){Label=lab;} private: char Label; }; class Graph { public: Graph(); ~Graph(); void addVertex(char lab); void addEdge(int Start,int End); //新增邊 void PrintMatrix(); //列印矩陣 private: Vertex* vertexList[MAX_VERTS]; //最多頂點的數量 int nVerts; //實際陣列頂點的數量 int adjMat[MAX_VERTS][MAX_VERTS]; //舉證 }; Graph::Graph() //建構函式 { nVerts=0; for(int i=0;i<MAX_VERTS;i++) for(int j=0;j<MAX_VERTS;j++) adjMat[i][j]=0; //全部初始化為0 } void Graph::addVertex(char lab) { vertexList[nVerts++]=new Vertex(lab); } void Graph::addEdge(int Start,int End) //增加一條邊 { adjMat[Start][End]=1; adjMat[End][Start]=1; //矩陣是對稱的 } void Graph::PrintMatrix() { for(int i=0;i<nVerts;i++) { for(int j=0;j<nVerts;j++) cout<<adjMat[i][j]<<" "; cout<<endl; } } Graph::~Graph() { for(int i=0;i<nVerts;i++) delete vertexList[i]; } int main() { Graph g; g.addVertex('A'); g.addVertex('B'); g.addVertex('C'); g.addVertex('D'); g.addVertex('E'); g.addEdge(0,1); //A-B g.addEdge(0,3); //A-D g.addEdge(1,0); //B-A g.addEdge(1,4); //B-E g.addEdge(2,4); //C-E g.addEdge(3,0); //D-A g.addEdge(3,4); //D-E g.addEdge(4,1); //E-B g.addEdge(4,2); //E-C g.addEdge(4,3); //E-D g.PrintMatrix(); //cout << "Hello world!" << endl; return 0; }