我的代码可以运行,但并非所有测试用例都适用。
我在这里尝试创建一个“布尔型ifparent数组”,它保存了我正在遍历的路径记录。
“布尔型visited数组”记录了所有已访问的顶点。
我正在使用堆栈进行深度优先搜索。
//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;
}