繁体   English   中英

如何在 DFS C++ 中检查 u、v 边是否连接

[英]How can check u , v edges connect or not in DFS C++

输入 v = 4, e = 3
边缘 (1,2)
边缘 (3,2)
边缘 (3,1)
我想检查 u = 3, v = 1
输出:是的,我想检查 u = 1, v = 3
输出:没有
有矩阵
0 1 0 0
0 0 0 0
1 1 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);
}

}

通常,这样的 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;
}

然后你就可以从主 function 调用它:

if (dfs(source_node, destination_node)) {
    std::cout << "yes\n";
} else {
    std::cout << "no\n";
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM