问题描述
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 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,dist))
return true;
}
}
return false;
}
让我困惑的那条线
return dfs(new_node,dist);
和
if (dfs(new_node,dist))
return true;
这段代码的作用是检查节点 source
和 dist
之间是否存在一条路径,使得路径的所有边都具有相同的颜色。第二个工作正常,但第一个不起作用。它们之间有区别吗?
解决方法
带有 #include <stdio.h>
void putPointer ( int *point,int num ) {
point = #
}
int main(void) {
int a = 42;
int *p;
// p = &a
putPointer( p,a );
printf( "%d\n",*p );
return 0;
}
的版本将总是从函数中返回,无论返回值是 return dfs(new_node,new_color,dist);
还是 true
。
然而,false
将进行递归调用,但仅在该调用返回 if (dfs(new_node,dist)) return true;
时才退出 for
循环(通过返回)。如果它返回 true
,则 false
循环继续下一次迭代。