Files
data-structures-and-algorithms/homework5/MatrixGraph.h
T
2024-12-06 01:56:28 +08:00

126 lines
3.8 KiB
C++

//
// Created by 31416 on 24-12-5.
//
#ifndef MATRIXGRAPH_H
#define MATRIXGRAPH_H
#include <functional>
#include <sstream>
#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; //是否连接
connection() {
weight = 0;
connected = false;
}
};
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>()); //添加一行
for (auto &row: matrix) {
row.resize(data.size(), connection()); // 扩展列
}
}
// 连接顶点
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;
}
}
// 打印matrix
string to_string() {
stringstream ss;
for (int i = 0; i < matrix.size(); ++i) {
for (int j = 0; j < matrix[i].size(); ++j) {
if (j == matrix[i].size() - 1) {
//判断是否哦是最后一个元素
if (isWeighted) {
// 判断是否加权
ss << matrix[i][j].connected << "|" << matrix[i][j].weight;
} else {
ss << matrix[i][j].connected;
}
} else {
if (isWeighted) {
ss << matrix[i][j].connected << "|" << matrix[i][j].weight << " ";
} else {
ss << matrix[i][j].connected << " ";
}
}
}
ss << endl;
}
return ss.str();
}
vector<T> DFS(int startID) {
if (startID >= matrix.size() || startID < 0) {
throw NodeIdOutOfRangeException("您提供的id不合理", 0X004);
}
vector<bool> visited(matrix.size(), false); //访问标记
vector<T> result;
function<void(int)> dfsHelper = [&](int node) {
visited[node] = true;
result.push_back(data.at(node));
for (int i = 0; i < matrix[node].size(); ++i) {
if (matrix[node][i].connected && !visited[i]) {
dfsHelper(i);
}
}
};
dfsHelper(startID);
return result;
}
};
#endif //MATRIXGRAPH_H