【发布时间】:2017-03-23 11:30:47
【问题描述】:
我在业余时间一直在尝试了解有关图遍历的更多信息,并且我正在尝试使用深度优先搜索来查找无向强连接图中起始节点和结束节点之间的所有简单路径。到目前为止,我一直在使用来自Print all paths from a given source to a destination 的代码,它仅用于有向图。
使用递归 DFS 的主要算法出现在这两个函数中:
void Graph::printAllPaths(int s, int d)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
// Create an array to store paths
int *path = new int[V];
int path_index = 0; // Initialize path[] as empty
// Initialize all vertices as not visited
for (int i = 0; i < V; i++)
visited[i] = false;
// Call the recursive helper function to print all paths
printAllPathsUtil(s, d, visited, path, path_index);
}
// A recursive function to print all paths from 'u' to 'd'.
// visited[] keeps track of vertices in current path.
// path[] stores actual vertices and path_index is current
// index in path[]
void Graph::printAllPathsUtil(int u, int d, bool visited[],
int path[], int &path_index)
{
// Mark the current node and store it in path[]
visited[u] = true;
path[path_index] = u;
path_index++;
// If current vertex is same as destination, then print
// current path[]
if (u == d)
{
for (int i = 0; i<path_index; i++)
cout << path[i] << " ";
cout << endl;
}
else // If current vertex is not destination
{
// Recur for all the vertices adjacent to current vertex
list<int>::iterator i;
for (i = adj[u].begin(); i != adj[u].end(); ++i)
if (!visited[*i])
printAllPathsUtil(*i, d, visited, path, path_index);
}
// Remove current vertex from path[] and mark it as unvisited
path_index--;
visited[u] = false;
}
这适用于有向图,但不适用于无向强连接图。
我想知道他们是否可以调整此代码以也适用于无向图?我觉得需要更多的回溯来探索更多可能的路径,但不确定如何解决这个问题。
任何帮助将不胜感激。
【问题讨论】:
-
无向图可以强连通吗?
-
也许我可以为此考虑回溯 DFS?
-
为什么不使用 BFS?
-
我不是 C++ 人,但从代码看来它应该可以工作。当你说它找到了一对,但忽略了其他 - 你能举个例子吗?
-
如果您想了解有关深度优先算法的更多信息,请查看来自youtube.com/playlist?list=PLUl4u3cNGP63gFHB6xb-kVBiQHYe_4hSi 的 MIT 课件,您可以在第 4 课中了解它。这是一个很棒的系列,尽管这里的重点是人工智能编程是算法方面,而不是任何“源代码或任意可编程语言”。这可能会帮助您更多地了解不同类型的树结构和遍历。
标签: c++ algorithm graph graph-algorithm depth-first-search