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:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
vector<string> answer;
int* visit = new int[n];
memset(visit,-1,sizeof(int)*n);
for(int i=0;i<n;i++)
{
string temp = string(n,'.');
temp[i] = 'Q';
visit[i] = 0;
answer.push_back(temp);
Queens(result,answer,visit,i,1,n);
visit[i] = -1;
answer.pop_back();
}
return result;
}
void Queens(vector<vector<string>>& result,vector<string>& answer,int* visit,int index,int count,int n)
{
if(count == n)
{
result.push_back(answer);
return;
}
bool flag;
for(int i =0;i<n;i++)
{
flag = true;
string temp = string(n,'.');
if(visit[i] != -1)
continue;
for(int j=0;j<n;j++)
{
if(visit[j] != -1)
{
if(abs(count-visit[j]) == abs(i-j))
{
flag = false;
break;
}
}
}
if(flag == false)
continue;
temp[i] = 'Q';
visit[i] = count;
answer.push_back(temp);
Queens(result,answer,visit,i,count+1,n);
visit[i] = -1;
answer.pop_back();
}
}
};
看着自己的代码闻到一股shit的味道,要使代码更加优雅整洁,修改后的代码如下:
class Solution {
public:
vector<vector<string>> solveNQueens(int n) {
vector<vector<string>> result;
vector<string> answer(n,string(n,'.'));
Queens(result,answer,0,n);
return result;
}
bool valid(vector<string>& answer,int row,int col,int n)
{
for(int i=0;i<n;i++)
if(answer[row][i] == 'Q')
return false;
for(int i=0;i<n;i++)
if(answer[i][col] == 'Q')
return false;
for(int i=row,j=col;i>=0&&j>=0;i--,j--)
if(answer[i][j] == 'Q')
return false;
for(int i=row,j=col;i>=0&&j<n;i--,j++)
if(answer[i][j] == 'Q')
return false;
return true;
}
void Queens(vector<vector<string>>& result,vector<string>& answer,int row,int n)
{
if(row == n)
{
result.push_back(answer);
return;
}
for(int col =0;col<n;col++)
{
if(valid(answer,row,col,n))
{
answer[row][col] = 'Q';
Queens(result,answer,row+1,n);
answer[row][col] = '.';
}
}
}
};
需要特别注意的是,在进行在斜线判断的时候,因为状态是从上一行往下一行传递,所以我们只需要判断45度和135度即可。