Search code examples
c++recursiondepth-first-search

What is the difference between the following two code snippets?


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:

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. The second one works fine, but the first one doesn't work. Is there a difference between them?


Solution

  • The version with return dfs(new_node, new_color, dist); will always return from the function after that call, whether that returned value is true or false.

    However, the 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. If it returns false, the for loop continues to its next iteration.