采用邻接矩阵或者邻接表创建一个无向网,设计一个算法,实现深度优先遍历和广度优先遍历。用C++语言写一个代码
时间: 2025-02-22 17:31:30 浏览: 46
在图论中,无向网络可以使用邻接矩阵或邻接表这两种数据结构表示。邻接矩阵是一个二维数组,其中行代表起点,列表示终点,值表示边的存在;邻接表则是一种链表结构,每个顶点指向其邻居的列表。
下面我会分别给出使用邻接矩阵和邻接表实现深度优先遍历(DFS)和广度优先遍历(BFS)的C++代码示例:
**邻接矩阵实现:**
```cpp
#include <vector>
using namespace std;
// 深度优先搜索
void dfs(vector<vector<bool>>& graph, int start) {
vector<bool> visited(graph.size(), false);
dfsHelper(graph, visited, start);
}
void dfsHelper(vector<vector<bool>>& graph, vector<bool>& visited, int vertex) {
visited[vertex] = true;
cout << vertex << " ";
for(int neighbor : graph[vertex]) { // 邻接矩阵的索引就是邻居
if(!visited[neighbor])
dfsHelper(graph, visited, neighbor);
}
}
// 广度优先搜索
void bfs(vector<vector<int>>& graph, int start) {
vector<int> queue;
queue.push_back(start);
vector<bool> visited(graph.size(), false);
while (!queue.empty()) {
int vertex = queue.front();
queue.pop_front();
if (!visited[vertex]) {
visited[vertex] = true;
cout << vertex << " ";
for (int neighbor : graph[vertex]) // 邻接矩阵访问邻居
queue.push_back(neighbor);
}
}
}
```
**邻接表实现:**
```cpp
#include <vector>
using namespace std;
// 定义节点结构
struct Node {
int dest;
Node* next;
};
// 类似于邻接矩阵,使用链表存储
class Graph {
private:
vector<Node*> adj; // 存储邻接节点
public:
void addEdge(int src, int dest) {
adj[src] = new Node{dest, adj[src]};
}
void dfs(Node* start) {
// 使用指针遍历链表
//...
}
void bfs() {
// 使用队列实现BFS
//...
}
};
```
在这个例子中,`dfs` 和 `bfs` 函数会接收对应的图结构(邻接矩阵或邻接表),并使用相应的数据结构来遍历图。你可以根据实际情况选择适合的数据结构。
阅读全文
相关推荐




















