以下两个代码片段有什么区别?
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);
的版本将 总是 return 来自调用后的函数,无论 returned 值是 true
或 false
.
然而,if (dfs(new_node, new_color, dist)) return true;
将进行递归调用,但 仅退出 for
循环 (通过 returning)如果该调用returns true
。如果它 returns false
,for
循环继续到下一次迭代。
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);
的版本将 总是 return 来自调用后的函数,无论 returned 值是 true
或 false
.
然而,if (dfs(new_node, new_color, dist)) return true;
将进行递归调用,但 仅退出 for
循环 (通过 returning)如果该调用returns true
。如果它 returns false
,for
循环继续到下一次迭代。