





class Solution {
public:
    vector<vector<string>> result;
    int** isValid;
    int* pos;
    void Sub(int s, int n)
    {
        if (s > n)
        {
            vector<string> ans;
            string str = "";
            for (int i = 0; i < n; i++)
            {
                for (int j = 0; j < n; j++)
                    if (j == pos[i])
                        str += "Q";
                    else
                        str += ".";
                ans.push_back(str);
                str = "";
            }
            result.push_back(ans);
            return;
        }
        else for (int i = 0; i < n; i++)
            if (!isValid[s-1][i])
            {
                pos[s-1] = i;
                for (int j = s; j < n; j++)
                {
                    isValid[j][i]++;
                }
                int x = s;
                int y = i-1;
                while (x < n && y >= 0)
                {
                    isValid[x][y]++;
                    x++;
                    y--;
                }
                x = s;
                y = i+1;
                while (x < n && y < n)
                {
                    isValid[x][y]++;
                    x++;
                    y++;
                }
                //Next Step
                Sub(s+1,n);
                for (int j = s; j < n; j++)
                {
                    isValid[j][i]--;
                }
                x = s;
                y = i-1;
                while (x < n && y >= 0)
                {
                    isValid[x][y]--;
                    x++;
                    y--;
                }
                x = s;
                y = i+1;
                while (x < n && y < n)
                {
                    isValid[x][y]--;
                    x++;
                    y++;
                }
            }
    }
    vector<vector<string>> solveNQueens(int n) {
        isValid = new int* [n];
        pos = new int [n];
        for (int i = 0; i < n; i++)
        {
            isValid[i] = new int [n];
            for (int j = 0; j < n; j++)
                isValid[i][j] = 0;
        }
        Sub(1, n);
        return result;
    }
};                










