简体   繁体   English

以下两个代码片段有什么区别?

[英]What is the difference between the following two code snippets?

DFS 1: DFS 1:

bool dfs(int source, int color, int dist) {
    vis[source] = true;
    if (source == dist)
        return true;
    for (auto x : adj[source]) {

        int new_node = x.first;
        if (!vis[new_node]) {
            int new_color = x.second;
            if (new_color == color)
                return dfs(new_node, new_color, dist);
                   
        }

    }
    return false;
}

DFS 2: DFS 2:

bool dfs(int source, int color, int dist) {
    vis[source] = true;
    if (source == dist)
        return true;
    for (auto x : adj[source]) {

        int new_node = x.first;
        if (!vis[new_node]) {
            int new_color = x.second;
            if (new_color == color)
                if (dfs(new_node, new_color, dist))
                       return true;
                   
        }

    }
    return false;
}

The line that confuses me让我困惑的线

return dfs(new_node, new_color, dist);

and

if (dfs(new_node, new_color, dist))
        return true;

What this code is doing check if there's a path between nodes source and dist such that all the edges of the path have the same color.这段代码正在做什么检查节点sourcedist之间是否存在路径,使得路径的所有边缘都具有相同的颜色。 The second one works fine, but the first one doesn't work.第二个工作正常,但第一个不起作用。 Is there a difference between them?它们之间有区别吗?

The version with return dfs(new_node, new_color, dist); return dfs(new_node, new_color, dist);的版本will always return from the function after that call, whether that returned value is true or false .在该调用之后将始终从 function 返回,无论该返回值是true还是false

However, the if (dfs(new_node, new_color, dist)) return true;但是, if (dfs(new_node, new_color, dist)) return true; will make the recursive call but only exit the for loop (by returning) if that call returns true .将进行递归调用,但仅在该调用返回true退出for循环(通过返回)。 If it returns false , the for loop continues to its next iteration.如果它返回false ,则for循环继续进行下一次迭代。

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

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