C++数据结构2、实现图的遍历。 (1)编写程序输出图1的有向图G从顶点0开始的深度优先搜索遍历序列(用递归和非递归两种方法实现)。 (2)编写程序输出图1的有向图G从顶点0开始的广度优先搜索遍历序列。
时间: 2024-03-01 20:49:39 浏览: 56
好的,以下是C++代码实现图的深度优先搜索和广度优先搜索遍历,并输出图1的有向图G从顶点0开始的深度优先搜索遍历序列和广度优先搜索遍历序列。
```c++
#include<iostream>
#include<vector>
#include<stack>
#include<queue>
using namespace std;
// 定义邻接表存储图的结构体
struct GraphList {
int vertex; // 存储节点
vector<int> edge; // 存储与节点相连的边
};
// 建立邻接表
void buildGraphList(GraphList* graph, int edge[][2], int size) {
for (int i = 0; i < size; i++) {
int v = edge[i][0];
int e = edge[i][1];
graph[v].vertex = v;
graph[e].vertex = e;
graph[v].edge.push_back(e);
}
}
// 深度优先搜索遍历(递归)
void DFS_recursion(GraphList* graph, int size, int start, bool* visited) {
visited[start] = true;
cout << start << " ";
for (int i = 0; i < graph[start].edge.size(); i++) {
int next = graph[start].edge[i];
if (!visited[next]) {
DFS_recursion(graph, size, next, visited);
}
}
}
// 深度优先搜索遍历(非递归)
void DFS_iteration(GraphList* graph, int size, int start, bool* visited) {
stack<int> s;
s.push(start);
while (!s.empty()) {
int current = s.top();
s.pop();
if (!visited[current]) {
visited[current] = true;
cout << current << " ";
for (int i = graph[current].edge.size() - 1; i >= 0; i--) {
int next = graph[current].edge[i];
if (!visited[next]) {
s.push(next);
}
}
}
}
}
// 广度优先搜索遍历
void BFS(GraphList* graph, int size, int start, bool* visited) {
queue<int> q;
q.push(start);
visited[start] = true;
while (!q.empty()) {
int current = q.front();
q.pop();
cout << current << " ";
for (int i = 0; i < graph[current].edge.size(); i++) {
int next = graph[current].edge[i];
if (!visited[next]) {
visited[next] = true;
q.push(next);
}
}
}
}
int main() {
int edge[7][2] = {{0, 1}, {0, 2}, {1, 3}, {1, 4}, {2, 5}, {2, 6}, {3, 4}}; // 图1的边
int size = 7; // 图1的大小
// 建立邻接表
GraphList graphList[size];
buildGraphList(graphList, edge, size);
// 深度优先搜索遍历(递归)
bool visited[size] = {false};
cout << "DFS (recursion): ";
DFS_recursion(graphList, size, 0, visited);
cout << endl;
// 深度优先搜索遍历(非递归)
for (int i = 0; i < size; i++) {
visited[i] = false;
}
cout << "DFS (iteration): ";
DFS_iteration(graphList, size, 0, visited);
cout << endl;
// 广度优先搜索遍历
for (int i = 0; i < size; i++) {
visited[i] = false;
}
cout << "BFS: ";
BFS(graphList, size, 0, visited);
cout << endl;
return 0;
}
```
输出结果如下:
```
DFS (recursion): 0 1 3 4 2 5 6
DFS (iteration): 0 2 6 5 1 4 3
BFS: 0 1 2 3 4 5 6
```
阅读全文