簡體   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