title: How to detect cycle using itarative approach
body: <p>I am trying to learn how to detect cycle. I see many example of using recursion but I want to implement in iterative way. Here is my code</p>
  <pre><code>public boolean cycleDetection(int[][] edges, int source ) {
       Map&lt;Integer, List&lt;Integer&gt;&gt; graph = new HashMap();
          for (int[] edge : edges) {
              graph.putIfAbsent(edge[0], new ArrayList());
              graph.get(edge[0]).add(edge[1]);
          }
          Stack&lt;Integer&gt; stack = new Stack();
          Set&lt;Integer&gt; visited = new HashSet();
          
          stack.push(source);
          visited.add(source);
          while(!stack.isEmpty()) {
              int curr = stack.pop();
              visited.add(curr);
              if(graph.containsKey(curr)) {
                  for(int i :  graph.get(curr)) {
                      
                      if(visited.contains(i)) {
                          return true;
                      }
                      stack.push(i);
                  }
              }
              
          }
      return false;
  }
  </code></pre>
  <p>It does not work as expected</p>
  <pre><code>    int[][] vertex = { {0 , 1 }, {0,3}, {1,2},{2,1} }; // Has Cycle
      int[][] vertex = { {0 , 1 }, {0,2}, {1,3},{2,3} }; // No Cycle
  </code></pre>
  <p>what logic I am missing here?</p>