The n-queens puzzle is the problem of placing n queens on an n x n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space, respectively.
Example 1:
Input: n = 4
Output: [[".Q..","...Q","Q...","..Q."],["..Q.","Q...","...Q",".Q.."]]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above
Example 2:
Input: n = 1
Output: [["Q"]]
Solution: (Backtracking)
Approach:
Try each possible cell and check if it is safe or not
check for row, col, diagonal
Diagonal Formula = row + col and row - col
class Solution
{
public:
vector<vector<string>> res;
bool isSafe(int row, int col, int n, vector<vector<int>> &v)
{
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
if (v[i][j] == 1)
{
if (i == row || j == col || row + col == i + j || row - col == i - j)
{
return false;
}
}
}
}
return true;
}
void findPos(int row, int n, vector<vector<int>> &v)
{
if (row == n)
{
vector<string> k;
for (int i = 0; i < n; i++)
{
string s = "";
for (int j = 0; j < n; j++)
{
if (v[i][j] == 1)
{
s = s + 'Q';
}
else
{
s = s + '.';
}
}
k.push_back(s);
}
res.push_back(k);
return;
}
for (int i = 0; i < n; i++)
{
if (isSafe(row, i, n, v))
{
v[row][i] = 1;
findPos(row + 1, n, v);
v[row][i] = 0;
}
}
return;
}
vector<vector<string>> solveNQueens(int n)
{
vector<vector<int>> v(n, vector<int>(n, 0));
findPos(0, n, v);
return res;
}
};