邻接矩阵类写完基础功能,邻接表类修复已存在连接判断bug
This commit is contained in:
+48
-13
@@ -6,30 +6,65 @@
|
||||
#define MATRIXGRAPH_H
|
||||
|
||||
#include<vector>
|
||||
|
||||
#include "GraphExceptions/InsertExistedConnectException.h"
|
||||
#include "GraphExceptions/NodeIdOutOfRangeException.h"
|
||||
#include "GraphExceptions/SameNodeConnectException.h"
|
||||
using namespace std;
|
||||
|
||||
template<typename T>
|
||||
class MatrixGraph {
|
||||
private:
|
||||
vector<T> data;
|
||||
vector<vector<bool> > matrix;
|
||||
int nodeCount;
|
||||
struct connection {
|
||||
T weight; //权
|
||||
bool connected; //是否连接
|
||||
};
|
||||
|
||||
vector<T> data; //顶点值
|
||||
vector<vector<connection> > matrix; //邻接矩阵
|
||||
bool flag; //是否为有向图
|
||||
bool isWeighted; //是否有权
|
||||
public:
|
||||
MatrixGraph() {
|
||||
matrix.clear();
|
||||
MatrixGraph(bool flag = false, bool isWeighted = false) {
|
||||
this->flag = flag;
|
||||
this->isWeighted = isWeighted;
|
||||
data.clear();
|
||||
nodeCount = 0;
|
||||
matrix.clear();
|
||||
}
|
||||
|
||||
// 添加顶点
|
||||
void insert(T value) {
|
||||
data.push_back(value);
|
||||
nodeCount++;
|
||||
matrix.push_back(vector<bool>(nodeCount, false));
|
||||
for(int i = 0; i < nodeCount-1; ++i) {
|
||||
matrix[i].push_back(false);
|
||||
matrix.push_back(vector<connection>(0, false)); //添加一行
|
||||
for (auto &row: matrix) {
|
||||
row.resize(data.size(), connection(0, false)); // 扩展列
|
||||
}
|
||||
}
|
||||
|
||||
// 连接顶点
|
||||
void connect(int id1, int id2, T weight = 0) {
|
||||
if (id1 > data.size() || id2 > data.size() || (id1 < 0 || id2 < 0)) {
|
||||
throw NodeIdOutOfRangeException("您提供的id不合理", 0X001);
|
||||
}
|
||||
if (id1 == id2) {
|
||||
throw SameNodeConnectException("禁止连接两个相同节点", 0x002);
|
||||
}
|
||||
if (matrix[id1][id2].connected) {
|
||||
if (matrix[id1][id2].weight == weight) {
|
||||
throw InsertExistedConnectException("禁止插入已存在的连接", 0x003);
|
||||
}
|
||||
matrix[id1][id2].weight = weight;
|
||||
if (flag == false) {
|
||||
matrix[id2][id1].weight = weight;
|
||||
}
|
||||
return;
|
||||
}
|
||||
matrix[id1][id2].connected = true;
|
||||
matrix[id1][id2].weight = weight;
|
||||
if (flag == false) {
|
||||
matrix[id2][id1].connected = true;
|
||||
matrix[id2][id1].weight = weight;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
#endif //MATRIXGRAPH_H
|
||||
|
||||
Reference in New Issue
Block a user