and运算符如何评估其参数。我有一个代码来检查图形是否是循环的。在这段代码中,if语句中有一个条件。而且我认为,就我能说的最好的是,它会在第一次遇到虚假表达时终止,而根本不会评估第二个表达式。
这是代码
bool Graph::isCyclicUtil(int v, bool *visited, bool *recStack){
if (visited[v] == false){
// Mark the current node as visited
visited[v] = true;
recStack[v] = true;
// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
for (i = adj[v].begin(); i != adj[v].end(); i++){
-------->**This and cond**if (!visited[*i] && isCyclicUtil(*i, visited, recStack))
return true;
else if (recStack[*i])
return true;
}
}
recStack[v] = false; // remove the vertex from the recursion stack
return false;
}
void Graph::printRecStack(bool *recStack){
cout << "\n \n";
for (int i = 0; i < V; i++){
if (recStack[i])
cout <<i<< "\n";
}
return;
}
bool Graph::isCyclic(){
// Mark all the vertices as not visited and not part of recursion stack
bool *visited = new bool[V];
bool *recStack = new bool[V];
for (int i = 0; i<V; i++){
visited[i] = false;
recStack[i] = false;
}
// Call the recursive helper function to detect cycle in different
// DFS trees.
if (isCyclicUtil(0,visited, recStack)){
printRecStack(recStack);
return true;
}
/*for (int i = 0; i < V; i++){
if (isCyclicUtil(i, visited, recStack))
printRecStack(recStack);
return true;
}*/
return false;
}
请在isCyclicUtil函数中观察if语句中的和条件。
如果你把一个简单的图形作为这样的测试用例:
0->1
1->2
2->0
2->3
3->3
为 0 调用 isCyclicUtil ,第一个 3 recStack 中的值显示为真。如果第二个表达式也在 if语句 中进行了评估,那么情况应该不是这样。因为 节点2 的调用将覆盖其 子0 。但由于循环从0开始,0已经被访问过,因此 recStack [0 ]应该初始化为false。但这并没有发生,所有这些都是真实的。好像 和 条件在遇到 已访问[0] 时立即终止,甚至没有调用再次 isCyclicUtil(0,visit,recStack )。