0

I have solved a problem that required me to find if the given directed graph had a cycle or not. The deal is, I used a recursive approach to solve it in the depth-first-search method. I was just wondering how the code would look in an Iterative approach of the same depth-first-search method. Here is my C++ code...

class Solution {
public:
    bool canFinish(int numCourses, vector<vector<int>>& prerequisites){
        // to make and adjacency list
        vector<int> adj[numCourses];
        for(auto x : prerequisites) adj[x[1]].push_back(x[0]);
    vector&lt;bool&gt; visited(numCourses, 0);
    vector&lt;bool&gt; dfsVisited(numCourses, 0);

    //iterating through all unvisited nodes
    for(int i = 0; i &lt; numCourses; i++)
        if(!visited[i] and isCycle(i, visited, dfsVisited, adj))
            return 0;

    return 1;
}

bool isCycle(int node, vector&lt;bool&gt;&amp; visited, vector&lt;bool&gt;&amp; dfsVisited, vector&lt;int&gt; adj[]){
    if(dfsVisited[node]) return 1;
    if(visited[node]) return 0;

    dfsVisited[node] = 1;
    visited[node] = 1;

    for(int x : adj[node])
        if(isCycle(x, visited, dfsVisited, adj))
            return 1;
    dfsVisited[node] = 0;
    return 0;
}

};

More specifically, when I use a stack, I am facing a problem in clearing the dfsVisited[node] while backtracking. Can someone please show me how an Iterative version of this code looks like? I will be grateful. Thank you

  • Coding questions are off-topic here. If you want to ask about an algorithm, please replace the code with concise pseudocode. If you want to ask about improving this code, that's off-topic here. – D.W. Aug 18 '21 at 21:09
  • That said, I think this is covered by other questions that ask how to convert recursion to iteration. – D.W. Aug 18 '21 at 21:10

0 Answers0