C++ 以下两段代码之间有什么区别?
DFS 1: DFS 2:C++ 以下两段代码之间有什么区别?,c++,recursion,depth-first-search,C++,Recursion,Depth First Search,DFS 1: 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 =
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(新节点、新颜色、距离)代码>
及
此代码正在执行的操作检查节点source
和dist
之间是否存在路径,以便路径的所有边都具有相同的颜色。第二个可以,但第一个不行。它们之间有区别吗?使用返回dfs的版本(新节点、新颜色、距离)无论返回值是true
还是false
,在该调用之后,code>都将始终从函数返回
但是,if(dfs(new_node,new_color,dist))返回true
将进行递归调用,但只有在调用返回true
时才退出for
循环(通过返回)。如果返回false
,则for
循环将继续进行下一次迭代
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;
}
if (dfs(new_node, new_color, dist))
return true;