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

51 lines
1.6 KiB
C++

// 利用邻接矩阵存储无向图,并从0号顶点开始进行深度优先遍历。
// 输入:
// 输入第一行是两个整数n e,其中n表示顶点数(则顶点编号为0至n-1),e表示图中的边数。之后有e行信息输入,每行输入表示一条边,格式是“顶点1 顶点2”,把边插入图中。如:
// 4 4
// 0 1
// 1 3
// 0 3
// 0 2
// 输出:
// 先输出存储图的邻接矩阵,同一行元素之间空1格,最后一个元素之后不要有空格。
// 之后空一行后输出从0号顶点开始的深度优先遍历序列,顶点编号之间空1格。
// 例如,对于上面的示例输入,输出为:
// 0 1 1 1
// 1 0 0 1
// 1 0 0 0
// 1 1 0 0
// 从顶点0开始的深度优先遍历序列:
// 0 1 3 2
// 说明
// 输入第1个4表示有4个顶点,第2个4表示有4条边。之后的4行输入代表4条边的顶点。
// 输出的前4行为邻接矩阵,之后空一行,然后输出的“0 1 3 2”是深度优先遍历序列。
//
#include <iostream>
#include"MatrixGraph.h"
using namespace std;
int main() {
MatrixGraph<int> graph = MatrixGraph<int>();
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;
vector<int> dfs = graph.DFS(0);
cout << "图的DFS序列为:" << endl;
vector<int>::iterator it;
for (it = dfs.begin(); it != dfs.end(); it++) {
cout << *it << " ";
}
cout << endl;
return 0;
}