我的代码有效,但不适用于所有测试用例。
我在这里尝试做的是创建一个“布尔值 ifparent 数组”,它保存我正在遍历的路径的记录。
“布尔访问数组”记录所有访问过的顶点。
我正在为 DFS 使用堆栈。
//v is no of vertex, adj[] is the adjacency matrix
bool isCyclic(int v, vector<int> adj[])
{
stack<int> st;
st.push(0);
vector<bool> visited(v, false);
vector<bool> ifparent(v, false);
int flag= 0;
int s;
while(!st.empty()){
s= st.top();
ifparent[s]= true;
visited[s]=true;
flag=0;
for(auto i: adj[s]){
if(visited[i]){
if(ifparent[i])
return true;
}
else if(!flag){
st.push(i);
flag= 1;
}
}
if(!flag){
ifparent[s]= false;
st.pop();
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)