圖的代碼實現 (鄰接矩陣)


本文的主要內容為:圖的C++代碼實現 (鄰接矩陣法),主要為各個類的聲明

 

邊類

 1 // Author: SihanLin
 2 // FileName: Edge.h
 3 
 4 // 圖的邊類
 5 class CEdge{
 6 public:
 7     int from;   // 起點
 8     int to;     // 終點
 9     int weight; // 權值
10 
11     explicit CEdge(int from = -1, int to = -1, int weight = 0){    // 構造函數
12         this->from = from;
13         this->to = to;
14         this->weight = weight;
15     }
16 
17     virtual ~CEdge(){   // 析構函數
18         
19     }
20 };

 

圖的抽象基類

 1 // Author: SihanLin
 2 // FileName: Graph.h
 3 
 4 // 圖的抽象基類
 5 class CGraph{
 6 protected:
 7     static const int UNVISITED;  // 頂點不可訪問 0
 8     static const int VISITED;    // 頂點可訪問 1
 9 public:
10     int numVertex;  // 頂點個數
11     int numEdge;    // 邊的個數
12     int* mark;      // 用於標記頂點是否已經被訪問
13     int* inDegree;  // 用於記錄頂點的入度
14 
15     explicit CGraph(int numVertex = 1); // 構造函數
16     virtual ~CGraph();                  // 析構函數
17 
18     int GetVerticesNum();
19     int GetEdgesNum();
20     int GetFromVertex(CEdge oneEdge);   // 獲取邊的起點
21     int GetToVertex(CEdge oneEdge);     // 獲取邊的終點
22     int GetWeight(CEdge oneEdge);       // 獲取邊的權值
23     bool IsEdge(CEdge oneEdge);         // 判斷是否是邊
24     void ResetMark();                   // 重新設置頂點是否被訪問的記錄
25 
26     // 純虛函數
27     virtual CEdge FirstEdge(int oneVertex) = 0;             // 獲取頂點的第一條邊
28     virtual CEdge NextEdge(CEdge preEdge) = 0;              // 獲取上一條邊的下一條邊
29     virtual void SetEdge(int from, int to, int weight) = 0; // 設置邊
30     virtual void delEdge(int from, int to) = 0;             // 刪除邊
31 };

 

圖的鄰接矩陣實現類

 1 // Author: SihanLin
 2 // FileName: GraphAdjacentMatrix.h
 3 
 4 
 5 #include "Graph.h"
 6 
 7 // 圖的鄰接矩陣實現類
 8 class CGraphM : public CGraph{
 9 private:
10     int** matrix;  // 指向二維鄰接矩陣的指針
11 public:
12     explicit CGraphM(int numVertex = 1);
13     ~CGraphM();
14 
15     CEdge FirstEdge(int oneVertex);                  // 找到頂點的第一條邊
16     CEdge NextEdge(CEdge preEdge);                   // 找到一條邊的下一條邊
17     void SetEdge(int from, int to, int weight);     // 設置邊
18     void delEdge(int from, int to);                 // 刪除邊
19 
20     void InitGraphM(int* pWArray2D);                // 初始化圖
21 
22     void DFS(int oneVertex);    // 深度優先搜索
23     void BFS(int oneVertex);    // 廣度優先搜索
24     void Visit(int oneVertex);  // 訪問頂點
25 
26     void Travel(int startVertex = 0, int travelType = 0); // 周游接口合並
27 };

 

具體的功能實現放在下期文章,讀者可先自行思考。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM