我的代码中针对 NQueens 问题的错误是什么?
what is the error in my code for NQueens problem?
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,则停止。
相关文章:
- Clang 8 带有静态 constexpr 和数组的链接器错误 - 错误是什么以及如何解决它?
- C++中的"expected unqualified-id"错误是什么?
- 谁能告诉我,程序中的错误是什么?该程序仅用于获取文件扩展名
- 我的代码中针对 NQueens 问题的错误是什么?
- 这个代码中的错误是什么,每次都会给我分段错误
- 'note: 候選人: Volume& Volume::operator=(const Volume&)'.这个错误是什么?
- 此气泡排序代码中的错误是什么?
- 第9行的给定代码中的错误是什么?
- C++ - "Incomplete type not allowed"错误是什么意思,我该如何修复它?
- 这个错误是什么?似乎没有理由出现
- 这个编译器错误是什么意思 - "qualified-id in declaration before ‘=’ token" C++?
- 这个boost.python程序中的错误是什么?
- C 如果该代码中的错误是什么
- TMB教程中的此编译错误是什么?
- 此代码运算符超载中的错误是什么?
- 英特尔SGX错误:8207错误是什么意思是当我无法正确加载飞地时
- 这个奇怪的"/usr/bin/ld: cannot find -lXAW_LIBRARY-NOTFOUND"错误是什么意思?
- 该代码的主要错误是什么,用于确定n`天后日期
- 错误 LNK2019:未解析的外部符号"外部"C"此错误是什么?
- 这个C++代码中的错误是什么