C++ DFS-查找源与目标相同的所有路径
我想使用DFS查找从源到目标的所有路径,其中源与目标相同 例如,A点到B点的邻接列表C++ DFS-查找源与目标相同的所有路径,c++,c++11,c++14,depth-first-search,C++,C++11,C++14,Depth First Search,我想使用DFS查找从源到目标的所有路径,其中源与目标相同 例如,A点到B点的邻接列表 0 - 1, 2 1 - 0, 3 2 - 0 3 - 1 因此,0到0的路径将是 0 1 0 0 2 0 0 1 3 1 0 这是一个可以打印所有路径的工作代码,但有些路径重复,有些路径错误 #include <iostream> #include <list> #include <vector> using namespace std; // This class
0 - 1, 2
1 - 0, 3
2 - 0
3 - 1
因此,0到0的路径将是
0 1 0
0 2 0
0 1 3 1 0
这是一个可以打印所有路径的工作代码,但有些路径重复,有些路径错误
#include <iostream>
#include <list>
#include <vector>
using namespace std;
// This class represents a directed graph using adjacency list representation
class Graph {
private:
// No. of vertices
int V;
// Pointer to an array containing adjacency lists
list<int> *adj;
// A function used by DFS
void DFSUtil(int v, int visited[], vector<int> &vec, int s, int d);
public:
// Constructor
Graph(int V);
// function to add an edge to graph
void addEdge(int v, int w);
// prints DFS traversal of the complete graph
void DFS();
};
Graph::Graph(int V) {
this->V = V;
this->adj = new list<int>[V];
}
void Graph::addEdge(int v, int w) {
// Add w to v’s list
adj[v].push_back(w);
adj[w].push_back(v);
}
Graph construct_graph() {
Graph g(4);
g.addEdge(0, 1);
g.addEdge(1, 3);
g.addEdge(0, 2);
return g;
}
void Graph::DFSUtil(int v, int visited[], vector<int> &paths, int s, int d) {
// Increase visited count of current node and add it to path
visited[v]++;
paths.push_back(v);
if((v == d) && (visited[s] == 2) && (paths.size() > 1)){
cout << "Path: ";
for(int i = 0; i < paths.size(); i++) {
cout << paths[i] << " ";
}
cout << endl;
} else {
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for(i = adj[v].begin(); i != adj[v].end(); ++i) {
if(visited[*i] < 2) {
DFSUtil(*i, visited, paths, s, d);
}
}
}
if(paths.size() > 1) {
visited[v]--;
paths.pop_back();
}
}
// The function to do DFS traversal. It uses recursive DFSUtil()
void Graph::DFS() {
// Mark all the vertices as not visited
int *visited = new int[V];
for(int i = 0; i < V; i++) {
visited[i] = 0;
}
// store potential path here till destination is reached
vector<int> paths;
// Call the recursive helper function to print DFS traversal
// starting from all vertices one by one
for (int i = 0; i < V; i++) {
if (visited[i] < 2) {
DFSUtil(i, visited, paths, 0, 0);
}
}
}
int main() {
// construct graph
// 0 ----- 1
// | |
// | |
// 2 3
Graph g = construct_graph();
// Time: O(V + E), Space: O(V^2)
g.DFS();
cout << endl;
return 0;
}
这就是我所期待的:
Path: 0 1 0
Path: 0 1 3 1 0
Path: 0 2 0
请注意,DFS将找到无穷多的形式为0 1 3 1 3 1 3 1 3 1 3 1 3 1 1 3 1 1 0的解决方案这正是我所期望的:--当程序中出现错误时,程序员会怎么做?你是否使用了调试器?Studie/Stury:C++不是java,你应该找到一种避免说<代码>新< /C>(因此,代码>删除< /代码>)的方法。在这种情况下,使用
std::vector
代替带有count的原始指针。当前,您正在析构函数中泄漏内存,并且有一个伪造的复制构造函数。您的Graph
类充满了内存泄漏。另外,如果您已经在使用std::vector
,为什么不在这里使用它<代码>此->调整=新列表[V]代码>--这可能是std::vector adj
然后使用图形(intv):adj(V){}
Path: 0 1 0
Path: 0 1 3 1 0
Path: 0 2 0