Files
data-structures-and-algorithms/homework5/MatrixGraph.h
T

71 lines
2.1 KiB
C++

//
// Created by 31416 on 24-12-5.
//
#ifndef MATRIXGRAPH_H
#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:
struct connection {
T weight; //权
bool connected; //是否连接
};
vector<T> data; //顶点值
vector<vector<connection> > matrix; //邻接矩阵
bool flag; //是否为有向图
bool isWeighted; //是否有权
public:
MatrixGraph(bool flag = false, bool isWeighted = false) {
this->flag = flag;
this->isWeighted = isWeighted;
data.clear();
matrix.clear();
}
// 添加顶点
void insert(T value) {
data.push_back(value);
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