[英]detect cycle in directed graph with non-recursive dfs
我的代碼有效,但不適用於所有測試用例。
我在這里試圖做的是創建一個'boolean ifparent array',該數組保存我正在遍歷的路徑的記錄。
“布爾訪問數組”保留所有訪問頂點的記錄。
我正在為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;
}
如果您喜歡使用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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.