title: recursive to iterative DFS python
body: <p>I am trying to convert recursive code to iterative. The task is to find the largest region (connected cells consisting of ones) in the grid.</p>
  
  <p>The code is referenced from here: <a href="https://www.geeksforgeeks.org/find-length-largest-region-boolean-matrix/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/find-length-largest-region-boolean-matrix/</a>
  I have tried using stack and a loop to replace recursion but it is not working</p>
  
  <p>here is the code I have tried and it does not reproduce the same result as with recursive approach.</p>
  
  <p>I have tested with</p>
  
  <pre><code>M = np.array([[0, 0, 1, 1, 0], [1, 0, 1, 1, 0], [0, 1, 0, 0, 0], [0, 0, 0, 0, 2],[0, 0, 0, 1, 0],[0, 0, 3, 0, 0]]) 
  
  def DFS(M, row, col, visited): 
      rowNbr = [-1, -1, -1, 0, 0, 1, 1, 1]  
      colNbr = [-1, 0, 1, -1, 1, -1, 0, 1]  
  
      # Mark this cell as visited  
      visited[row][col] = True
      stack = [] 
  
      for k in range(8): 
          if (isSafe(M, row + rowNbr[k],  
                     col + colNbr[k], visited)): 
  
              stack.push(M[row][col])
              row = row + rowNbr[k]
              col = col + colNbr[k]
              for k in range(8): 
                  if (isSafe(M, row + rowNbr[k],  
                      col + colNbr[k], visited)):
                      stack.push(M[row][col])
  </code></pre>