class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
N = n;
vector<string> col(n, string(n, '.'));
dfs(-1, col);
return _ret;
}
void dfs(int i, vector<string>& col)
{
if (i == N - 1)
{
#ifdef PRINT
cout << ++cnt << "===\n";
for (auto v : col)
{
cout << v << "\n";
}
cout << "\n";
#endif
_ret.push_back(col);
}
else
{
for (size_t j = 0; j < N; j++)
{
col[i + 1] = string(N, '.');
col[i+1][j] = 'Q';
if(isPromise(i+1, j, col))
dfs(i + 1, col);
}
}
}
bool isPromise(int i, int j, vector<string>& col)
{
for (int k = 0; k < i; k++)
{
if (col[k][j] == col[i][j])
{
return false;
}
int d = abs(i - k);
if ( (j -d >= 0 && col[i][j] == col[k][ abs( j-d )])
|| (j + d < col.size() && col[i][j] == col[k][j + d]) )
{
return false;
}
}
return true;
}
int N;
int cnt = 0;
vector<vector<string>> _ret;
};