实验五完成

This commit is contained in:
2024-12-06 01:56:28 +08:00
parent ee2503b5a7
commit a6b36e0de5
3 changed files with 48 additions and 17 deletions
+25 -1
View File
@@ -5,6 +5,7 @@
#ifndef MATRIXGRAPH_H
#define MATRIXGRAPH_H
#include <functional>
#include <sstream>
#include<vector>
@@ -48,7 +49,7 @@ public:
// 连接顶点
void connect(int id1, int id2, T weight = 0) {
if (id1 > data.size() || id2 > data.size() || (id1 < 0 || id2 < 0)) {
if (id1 >= data.size() || id2 >= data.size() || (id1 < 0 || id2 < 0)) {
throw NodeIdOutOfRangeException("您提供的id不合理", 0X001);
}
if (id1 == id2) {
@@ -97,5 +98,28 @@ public:
}
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