Vip*_*pul 1 c++ algorithm graph-theory depth-first-search
我的代码有效,但不适用于所有测试用例。
我在这里尝试做的是创建一个“布尔值 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)
gim*_*ger 13
如果您喜欢使用 DFS 进行循环检测的迭代方法,我会向您推荐一个稍微重新组织的代码版本,其中我以更常见的方式编写 DFS。
bool isCyclic(int V, vector<int> adj[]) {
vector<bool> visited (V, false);
vector<bool> on_stack (V, false);
stack<int> st;
for (int w = 0; w < V; w++) {
if (visited[w])
continue;
st.push(w);
while (!st.empty()) {
int s = st.top();
if (!visited[s]) {
visited[s] = true;
on_stack[s] = true;
} else {
on_stack[s] = false;
st.pop();
}
for (const auto &v : adj[s]) {
if (!visited[v]) {
st.push(v);
} else if (on_stack[v]) {
return true;
}
}
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)