我的代码中针对 NQueens 问题的错误是什么?

what is the error in my code for NQueens problem?

本文关键字:错误 是什么 问题 NQueens 代码 我的      更新时间:2023-10-16
vector<vector<string>> ans;
void addtoans(vector<vector<int>> &board, int n){
vector<string> row;
string s = "";
int i,j;
for(i = 0;i < n;i++){
for(j = 0;j < n;j++){
if(board[i][j] == 1)
s = s + 'Q';
else
s = s + '.';
}
row.push_back(s);
s = "";
}
ans.push_back(row);
return;
}
bool issafe(vector<vector<int>> &board, int row, int col, int n){
int i,j;
for(i = 0;i < row;i++)
if(board[i][col] == 1)
return false;
int x = row, y = col;
while(x >= 0 && y >= 0){
if(board[x][y] == 1)
return false;
x--; y--;
}
x = row; y = col;
while(x >= 0 && y < n){
if(board[x][y] = 1)
return false;
x--; y++;
}
return true;
}
bool solveNqueen(vector<vector<int>> &board, int i,int n){
if(i == n)
return true;
int j;
for(j = 0;j < n;j++){
if(issafe(board,i,j,n)){
board[i][j] = 1;
bool nextqueenpos = solveNqueen(board, i+1, n);
if(nextqueenpos)
return true;
board[i][j] = 0;
}
}
return false;
}
vector<vector<string>> solveNQueens(int n) {
int i, j;
for(i = 0;i < n;i++){
vector<vector<int>>board(n,vector<int>(n,0));
board[0][i] = 1;
bool ispossible = solveNqueen(board,1,n);
if(ispossible){
addtoans(board,n);
}
}
return ans;
}

n-queens问题:n-queens难题是将n个女王放在n×n个棋盘上的问题,这样就不会有两个女王互相攻击。 这是我在leetcode上写的代码段。我的输出是 [],这是错误的。我的代码返回空白向量。请帮我找到代码中的错误。

很难想象确切的问题输入和输出类型,但是,假设第一个女王的位置是(x=0,y=0(,你可以将下一个女王放在(x=x+1,y=y+2(或(x=x+2,y=y+1(。如果 x 或 y 值大于 n,则停止。