L51: N-Queens
The n-queens puzzle is the problem of placing n queens on an n×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.
For example,
There exist two distinct solutions to the 4-queens puzzle:
[
[“.Q..”, // Solution 1
“…Q”,
“Q…”,
“..Q.”],
[“..Q.”, // Solution 2
“Q…”,
“…Q”,
“.Q..”]
]
解题思路:典型的回溯法,可用递归或非递归解决
class Solution {
public:
bool isAttack(vector<int> queens, int k)
{
if(k == 0)
return false;
for (int i=0; i<k; i++)
{
if(queens[k] == queens[i] || abs(k-i) == abs(queens[k]-queens[i]))
return true;
}
return false;
}
void showQueens(vector<int> queens, vector<vector<string> >& result){
int n = queens.size();
vector<string> vec(n, string(n,‘.‘));
for(int i = 0; i < n; i++)
vec[i][queens[i]] = ‘Q‘;
result.push_back(vec);
}
vector<vector<string> > solveNQueens(int n) {
vector<vector<string> > result;
vector<int> queens(n,0);
if(n == 1)
{
vector<string> vec(1, string(‘Q‘));
result.push_back(vec);
return result;
}
int i = 0;
while(1)
{
while(i < n)
{
while(queens[i] == n)
{
queens[i--] = 0;
if(i == -1)
return result;
queens[i]++;
}
if(isAttack(queens,i))
queens[i]++;
else
i++;
}
showQueens(queens,result);
queens[n-1] = 0;
i = n-2;
queens[i]++;
}
}
};
时间: 2024-10-23 12:25:16