实现图的存储,输出存储结构示意图; 输出对建立的图进行深度优先搜索和广度优先搜索所得的遍历序列。
时间: 2024-02-13 19:04:37 浏览: 63
好的,邻接表是一种常见的图的存储结构。它将每个顶点的所有邻接点存储在一个链表中,因此可以很容易地遍历每个顶点的邻接点。下面是一个邻接表的存储结构示意图:
```C++
struct Edge {
int dest;
int weight;
Edge* next;
};
struct Vertex {
int id;
Edge* head;
};
class Graph {
public:
Graph(int num_vertices) {
this->num_vertices = num_vertices;
vertices = new Vertex[num_vertices];
for (int i = 0; i < num_vertices; i++) {
vertices[i].id = i;
vertices[i].head = nullptr;
}
}
void add_edge(int src, int dest, int weight) {
Edge* new_edge = new Edge;
new_edge->dest = dest;
new_edge->weight = weight;
new_edge->next = vertices[src].head;
vertices[src].head = new_edge;
}
void dfs(int start) {
bool* visited = new bool[num_vertices];
for (int i = 0; i < num_vertices; i++) {
visited[i] = false;
}
dfs_util(start, visited);
delete[] visited;
}
void bfs(int start) {
bool* visited = new bool[num_vertices];
for (int i = 0; i < num_vertices; i++) {
visited[i] = false;
}
queue<int> q;
visited[start] = true;
q.push(start);
while (!q.empty()) {
int curr = q.front();
q.pop();
cout << curr << " ";
Edge* edge = vertices[curr].head;
while (edge != nullptr) {
int dest = edge->dest;
if (!visited[dest]) {
visited[dest] = true;
q.push(dest);
}
edge = edge->next;
}
}
delete[] visited;
}
private:
int num_vertices;
Vertex* vertices;
void dfs_util(int curr, bool* visited) {
visited[curr] = true;
cout << curr << " ";
Edge* edge = vertices[curr].head;
while (edge != nullptr) {
int dest = edge->dest;
if (!visited[dest]) {
dfs_util(dest, visited);
}
edge = edge->next;
}
}
};
```
在这个示例代码中,`Graph` 类实现了邻接表存储结构,并且提供了深度优先搜索和广度优先搜索两个方法。在构造函数中,我们初始化了每个顶点的链表头指针为 `nullptr`。在添加边的方法中,我们创建一个新的边,并将它加到源顶点的链表头。在深度优先搜索和广度优先搜索方法中,我们都使用一个 `visited` 数组来记录每个顶点是否被访问过。在深度优先搜索中,我们首先将起始顶点标记为已访问,并输出它的编号,然后递归地遍历它的邻接点。在广度优先搜索中,我们使用一个队列来维护待访问的顶点,每次取出队首元素并输出,然后将它的邻接点加入队列中。
阅读全文