C++有向邻接表,std::vector<std::vector<unsigned int>> graph,写一个函数,可以输出多个路径
时间: 2024-12-25 19:27:26 浏览: 7
C++中,要实现输出从一个有向邻接表(`std::vector<std::vector<unsigned int>> graph`)到另一个节点的多条路径,我们可以使用深度优先搜索(DFS)。这里有一个简单的示例,它遍历图并打印所有从起点到终点的不同路径:
```cpp
#include <iostream>
#include <vector>
#include <stack>
void DFS(std::vector<std::vector<unsigned int>>& graph, unsigned int start, unsigned int end, std::string path, std::vector<std::string>& paths) {
if (start == end) {
paths.push_back(path);
return;
}
for (unsigned int neighbor : graph[start]) {
DFS(graph, neighbor, end, path + " -> " + std::to_string(neighbor), paths);
}
}
std::vector<std::string> findPaths(const std::vector<std::vector<unsigned int>>& graph, unsigned int start, unsigned int end) {
std::vector<std::string> paths;
std::vector<bool> visited(graph.size(), false);
DFS(graph, start, end, std::to_string(start), paths);
return paths;
}
int main() {
std::vector<std::vector<unsigned int>> graph = {{1, 2}, {2, 3}, {3, 4}, {4, 5}}; // 示例图
unsigned int start = 1, end = 5;
std::vector<std::string> paths = findPaths(graph, start, end);
for (const auto& path : paths) {
std::cout << "Path: " << path << std::endl;
}
return 0;
}[^1]
阅读全文