title: Adding all solutions of N Queen Problem to an arrayList
body: <p>The n-queens puzzle is the problem of placing n queens on a (n×n) chessboard such that no two queens can attack each other.</p>
  <p>I used backtracking to solve the problem. But I ran in a strange issue.</p>
  <p>Below is the code I wrote:</p>
  <pre><code>import java.util.ArrayList;
  
  public class NQueenProblem {
  
      static ArrayList&lt;ArrayList&lt;Integer&gt;&gt; ans = new ArrayList&lt;ArrayList&lt;Integer&gt;&gt;();
  
      static ArrayList&lt;ArrayList&lt;Integer&gt;&gt; nQueen(int n) {
  
          ArrayList&lt;Integer&gt; positions = new ArrayList&lt;Integer&gt;();
          //boolean[][] placed = new boolean[n][n];
          solveNQueenRec(n, 0, new boolean[n][n], positions);
          //for dubugging purpose. This prints empty arrays. not able to understand why?
          for (ArrayList&lt;Integer&gt; list : ans)
              System.out.println(list);
          return ans;
      }
  
      static void solveNQueenRec(int n, int col, boolean[][] placed, ArrayList&lt;Integer&gt; positions) {
          if (col == n) {
              //for debugging process
              System.out.println(&quot;Adding &quot; + positions);
              ans.add(positions);
              System.out.println(&quot;Added &quot; + positions);
          }
          for (int row = 0; row &lt; n &amp;&amp; col &lt; n; row++) {
              if (isSafe(row, col, placed, n)) {
                  placed[row][col] = true;
                  positions.add(row + 1);
                  solveNQueenRec(n, col + 1, placed, positions);
                  placed[row][col] = false;
                  positions.remove(positions.size() - 1);
              }
          }
          // return null;
      }
  
      private static boolean isSafe(int row, int col, boolean[][] placed, int n) {
          boolean safe = true;
          // checking if exists in same row
          for (int i = 0; i &lt; col; i++) {
              if (placed[row][i])
                  safe = false;
          }
          // checking for upper diagonal
          for (int i = row, j = col; i &gt;= 0 &amp;&amp; j &gt;= 0; i--, j--) {
              if (placed[i][j])
                  safe = false;
          }
          // checking for lower diagonal
          for (int i = row, j = col; i &lt; n &amp;&amp; j &gt;= 0; i++, j--) {
              if (placed[i][j])
                  safe = false;
          }
          return safe;
      }
  
      public static void main(String[] args) {
          // TODO Auto-generated method stub
          nQueen(4);
  
      }
  
  }
  </code></pre>
  <p>What I am not able to understand is why my ans is empty when I could see in logs list being added to my ans.  Am I doing some silly mistake. Please help me with the issue. If possible please help me with links to understand the issue and how could I avoid these issues in future.</p>