[英]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;
}
让我困惑的线
return dfs(new_node, new_color, dist);
和
if (dfs(new_node, new_color, dist))
return true;
这段代码正在做什么检查节点source
和dist
之间是否存在路径,使得路径的所有边缘都具有相同的颜色。 第二个工作正常,但第一个不起作用。 它们之间有区别吗?
return dfs(new_node, new_color, dist);
的版本在该调用之后将始终从 function 返回,无论该返回值是true
还是false
。
但是, if (dfs(new_node, new_color, dist)) return true;
将进行递归调用,但仅在该调用返回true
时退出for
循环(通过返回)。 如果它返回false
,则for
循环继续进行下一次迭代。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.