title: Detect cycle in a directed graph using iterative stack approach
body: <p>This is what I tried:</p>
  <pre class="lang-py prettyprint-override"><code>VISITED = 1
  UNVISITED = -1
  VISITING = 0
  
  
  def dfs(g, start, num):
      
      state = {}
      for i in range(num):
          state[i] = UNVISITED
      
      
      stack = [start]
      while(stack != []):
          node = stack.pop()
          
          if(state[node] == VISITED):
              continue
  
          state[node] = VISITING
          
          if(node in g):
              for i in g[node]:
                  stack.append(i)
                  if(state[i] == VISITED):
                      return True
                  
          state[node] = VISITED
   
  def detect_cycle(n, edges):
          
      g = {}
      # adjacency list
      for (x, y) in edges:
          g[x] = g.get(x, []) + [y]
  
      for i in range(n):
          if(i in g):
              if(dfs(g, i, n) == True):
                  return True   
      return False   
              
  print(detect_cycle(5, [[1,4],[2,4],[3,1],[3,2]])) # outputs True (should be false)
  </code></pre>
  <p>Image of the graph:</p>
  <p><img src="https://i.stack.imgur.com/iePse.png" alt="The graph" /></p>
  <p>The above example where <code>edges = [[1,4],[2,4],[3,1],[3,2]]</code> doesn't contain a cycle but it returns <code>True</code>. So my algorithm does not work for that case.</p>
  <p>I'm trying to use the coloring graph detect cycle algorithm but I am unsure how to do that without recursion.</p>
  <p>The algorithm I'm trying to follow but iteratively: <a href="https://stackoverflow.com/questions/31542031/detecting-a-cycle-in-a-directed-graph-using-dfs/31543297">Detecting a cycle in a directed graph using DFS?</a></p>