[英]How can check u , v edges connect or not in DFS C++
input v = 4, e =3输入 v = 4, e = 3
edges (1,2)边缘 (1,2)
edges (3,2)边缘 (3,2)
edges (3,1)边缘 (3,1)
i want to check u = 3, v = 1我想检查 u = 3, v = 1
out put: yes and i want check u = 1, v = 3输出:是的,我想检查 u = 1, v = 3
out put: no输出:没有
have matrix有矩阵
0 1 0 0 0 1 0 0
0 0 0 0 0 0 0 0
1 1 0 0 1 1 0 0
0 0 0 0 0 0 0 0
void DFS(int i,int t)
{
int j;
visited[i] = 1;
cout << i+1 << " ";
if(i == t)
cout << "yes";
for(j=0;j<V;j++)
{
if(G[i][j]==1 && visited[j] == 0)
DFS(j,t,x);
}
}
Normally a DFS implementation for something like this might look something like (I haven't tested it so there may be an issue or two):通常,这样的 DFS 实现可能看起来像(我还没有测试过,所以可能有一两个问题):
bool dfs(int this_node, int destination_node) {
// base case where this node is the destination node
if (this_node == destination_node) return true;
// mark this node as visited
visited[this_node] = true;
// go deeper in the search
for (size_t next_node = 0; next_node < V; ++ next_node) {
// skip the search if this node isn't a valid child
if (visited[next_node] || !g[this_node][next_node]) {
continue;
}
// here is the recursive step
if (dfs(next_node, destination_node)) {
return true;
}
}
// if we made it all the way here, then the search failed to reach the destination
return false;
}
Then you'd be able to call this from the main function:然后你就可以从主 function 调用它:
if (dfs(source_node, destination_node)) {
std::cout << "yes\n";
} else {
std::cout << "no\n";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.