实验五第二题做完

This commit is contained in:
2024-12-05 18:53:08 +08:00
parent f2590db299
commit b8cde94091
2 changed files with 68 additions and 13 deletions
+33
View File
@@ -5,6 +5,7 @@
#ifndef LIST_GRAPH_H #ifndef LIST_GRAPH_H
#define LIST_GRAPH_H #define LIST_GRAPH_H
#include <queue>
#include <sstream> #include <sstream>
#include<vector> #include<vector>
@@ -116,6 +117,38 @@ public:
} }
return ss.str(); return ss.str();
} }
vector<T> BFS(int startId) {
if (startId >= nodes.size() || startId < 0) {
throw NodeIdOutOfRangeException("起始节点id超出范围", 0X004);
}
vector<bool> visited(nodes.size(), false);
queue<int> q;
vector<T> result;
// 标记起始节点已访问
visited[startId] = true;
q.push(startId);
while (!q.empty()) {
int currentId = q.front();
q.pop();
result.push_back(currentId);
node* current = nodes.at(currentId);
// 跳过id节点和值节点
current = current->next->next;
while (current != NULL) {
int neighborId = current->data;
if (!visited[neighborId]) {
visited[neighborId] = true;
q.push(neighborId);
}
current = current->next;
}
}
return result;
}
}; };
+35 -13
View File
@@ -1,29 +1,51 @@
// 利用邻接矩阵存储无向图,并从0号顶点开始进行度优先遍历。 // 利用邻接存储无向图,并从0号顶点开始进行广度优先遍历。
// 输入: // 输入:
// 输入第一行是两个整数n e,其中n表示顶点数(则顶点编号为0至n-1),e表示图中的边数。之后有e行信息输入,每行输入表示一条边,格式是“顶点1 顶点2”,把边插入图中。如: // 输入第一行是两个整数n e,其中n表示顶点数(则顶点编号为0至n-1),e表示图中的边数。
// 之后有e行输入,每行输入表示一条边,格式是“顶点1 顶点2”,把边插入图中。在链表中插入元素时,在链表头部插入。需要注意,由于是无向图,因此同一条边需要在两条链表中都插入。
// 例如:
// 4 4 // 4 4
// 0 1 // 0 1
// 1 3 // 1 3
// 0 3 // 0 3
// 0 2 // 0 2
// 输出: // 输出:
// 先输出存储图的邻接矩阵,同一行元素之间空1格,最后一个元素之后不要有空格。 // 先按0至n-1输出存储图的邻接表,每个链表占1行,同一行元素之间空1格,最后一个元素之后不要有空格。先输出顶点编号,之后按链表顺序输出相邻顶点编号。
// 之后空一行后输出从0号顶点开始的度优先遍历序列,顶点编号之间空1格。 // 之后空一行后输出从0号顶点开始的广度优先遍历序列,顶点编号之间空1格。
// 例如,对于上面的示例输入,输出为: // 例如,对于上面的示例输入,输出为:
// 0 1 1 1 // 0 2 3 1
// 1 0 0 1 // 1 3 0
// 1 0 0 0 // 2 0
// 1 1 0 0 // 3 0 1
// 从顶点0开始的度优先遍历序列: // 从顶点0开始的广度优先遍历序列:
// 0 1 3 2 // 0 2 3 1
// 说明 // 说明
// 输入第1个4表示有4个顶点,第2个4表示有4条边。之后的4行输入代表4条边的顶点。 // 输入第1个4表示有4个顶点,第2个4表示有4条边。之后的4行输入代表4条边的顶点。输出前4行为邻接表中的4个链表,之后空一行,然后输出的“0 2 3 1”是深度优先遍历序列。
// 输出的前4行为邻接矩阵,之后空一行,然后输出的“0 1 3 2”是深度优先遍历序列。
#include"ListGraph.h" #include"ListGraph.h"
#include<iostream> #include<iostream>
using namespace std; using namespace std;
int main() { int main() {
ListGraph<int> graph=ListGraph<int>();
int n,e;
cin>>n>>e;
for(int i=0;i<n;i++) {
graph.insert(i);
}
int id1,id2;
for(int i=0;i<e;i++) {
cin>>id1>>id2;
graph.connect(id1,id2);
}
cout<<"邻接表:"<<endl;
cout<<graph.to_string()<<endl;
cout<<"BFS序列:"<<endl;
vector<int> bfs=graph.BFS(0);
vector<int>::iterator it;
for(it=bfs.begin();it!=bfs.end();++it) {
cout<<*it<<" ";
}
cout<<endl;
return 0; return 0;
} }