diff --git a/homework5/MatrixGraph.h b/homework5/MatrixGraph.h index 7804259..2840b0c 100644 --- a/homework5/MatrixGraph.h +++ b/homework5/MatrixGraph.h @@ -5,6 +5,7 @@ #ifndef MATRIXGRAPH_H #define MATRIXGRAPH_H +#include #include #include "GraphExceptions/InsertExistedConnectException.h" @@ -18,6 +19,10 @@ private: struct connection { T weight; //权 bool connected; //是否连接 + connection() { + weight = 0; + connected = false; + } }; vector data; //顶点值 @@ -35,9 +40,9 @@ public: // 添加顶点 void insert(T value) { data.push_back(value); - matrix.push_back(vector(0, false)); //添加一行 + matrix.push_back(vector()); //添加一行 for (auto &row: matrix) { - row.resize(data.size(), connection(0, false)); // 扩展列 + row.resize(data.size(), connection()); // 扩展列 } } @@ -66,5 +71,31 @@ public: 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(); + } }; #endif //MATRIXGRAPH_H diff --git a/homework5/test1.cpp b/homework5/test1.cpp index 72d9bca..e8f9361 100644 --- a/homework5/test1.cpp +++ b/homework5/test1.cpp @@ -24,6 +24,20 @@ #include #include"MatrixGraph.h" using namespace std; + int main() { + MatrixGraph graph = new MatrixGraph(); + int n, e; + cin >> n >> e; + for (int i = 0; i < n; i++) { + graph.insert(i); + } + for (int i = 0; i < e; i++) { + int id1, id2; + cin >> id1 >> id2; + graph.connect(id1, id2); + } + cout << "图的邻接矩阵为:" << endl; + cout << graph.to_string() << endl; return 0; -} \ No newline at end of file +}