<p>The <strong>n-queens</strong> puzzle is the problem of placing <code>n</code> queens on an <code>n x n</code> chessboard such that no two queens attack each other.</p>

<p>Given an integer <code>n</code>, return <em>the number of distinct solutions to the&nbsp;<strong>n-queens puzzle</strong></em>.</p>

<p>&nbsp;</p>
<p><strong class="example">Example 1:</strong></p>
<img alt="" src="https://assets.leetcode.com/uploads/2020/11/13/queens.jpg" style="width: 600px; height: 268px;" />
<pre>
<strong>Input:</strong> n = 4
<strong>Output:</strong> 2
<strong>Explanation:</strong> There are two distinct solutions to the 4-queens puzzle as shown.
</pre>

<p><strong class="example">Example 2:</strong></p>

<pre>
<strong>Input:</strong> n = 1
<strong>Output:</strong> 1
</pre>

<p>&nbsp;</p>
<p><strong>Constraints:</strong></p>

<ul>
	<li><code>1 &lt;= n &lt;= 9</code></li>
</ul>

typedef struct node{
    pair<int,int> pos;//last node
    vector<vector<bool>> map;//for restore the state
}node;


class Solution {
public:
    int pos[8][2]={{1,0},{1,-1},{1,1},{0,1},{0,-1},{-1,0},{-1,-1},{-1,1}};
    
    void put_queen( vector<vector<bool>> &map, int pos_x , int pos_y ){//ensure the pos can be put
        map[pos_y][pos_x]=false;
        for( auto dir : pos ){
            for( int len=1;pos_x+dir[0]*len>=0&&pos_x+dir[0]*len<map.size()&&pos_y+dir[1]*len>=0&&pos_y+dir[1]*len<map.size(); len++){
                map[pos_y+dir[1]*len][pos_x+dir[0]*len]=false;
            }
        }
    }
    
    int totalNQueens(int n) {
        vector<vector<bool>> map(n,vector<bool>(n,true));
        stack<node> s;
        for( int i=0;i<n;i++ ){
            vector<vector<bool>> copy(map);
            put_queen(copy,i,0);
            s.push({{i,0},copy});
        }//base case

        int res=0;
        
        while(!s.empty()){
            //get top node
            int curr_x=s.top().pos.first;
            int curr_y=s.top().pos.second;
            vector<vector<bool>> ref(s.top().map);
            s.pop();
            if( curr_y == n-1 ){
                res++;
                continue;
            }
            for( int pos_x=0;pos_x<n;pos_x++){//push all the valid nodes in the next line
                if( ref[curr_y+1][pos_x] ){
                    vector<vector<bool>> copy(ref);
                    put_queen(copy,pos_x,curr_y+1);
                    s.push({{pos_x,curr_y+1},copy});
                }
            }
        }
        return res;
    }
};
37742