class Solution {
public:
Solution()
{
for(int i=0; i<16; i++)
arr[i] = 0;
}
vector<vector<string>> solveNQueens(int n)
{
vector<vector<string>> vecRes;
vector<string> board(n, string(n, '.'));
fun(vecRes, board, 0);
return vecRes;
}
private:
void fun(vector<vector<string>>& result, vector<string>& board, int curRow)
{
int size = board.size();
for(int col=0; col<size; col++)
{
if(isValid(board, curRow, col))
{
board[curRow][col] = 'Q';
arr[col] = 1;
if(curRow == size-1)
result.push_back(board);
else
fun(result, board, curRow+1);
board[curRow][col] = '.';
arr[col] = 0;
}
}
}
bool isValid(vector<string>& board, int i, int j)
{
int size = board.size();
int row = 0;
int col = 0;
if(arr[j] == 1)
return false;
for(row=i-1, col=j-1; row>=0&&col>=0; row--,col--)
if(board[row][col] == 'Q')
return false;
for(row=i-1, col=j+1; row>=0&&col<size; row--,col++)
if(board[row][col] == 'Q')
return false;
return true;
}
int arr[16];
};
LeetCode 51: N-Queens
最新推荐文章于 2022-01-06 10:11:48 发布