【发布时间】:2021-12-18 12:27:31
【问题描述】:
我正在尝试解决这个 nQueens 问题,我的代码如下所示:
class Solution {
public:
vector<vector<string>> ans;
bool canPlace(vector<string> &board, int row, int col, int n){
//upper left diagonal
int rowIndex = row;
int colIndex = col;
while(rowIndex >= 0 and colIndex >= 0){
if(board[rowIndex][colIndex] == 'Q'){
return false;
}
rowIndex--;
colIndex--;
}
// left side
rowIndex = row;
colIndex = col;
while(colIndex >= 0){
if(board[rowIndex][colIndex] == 'Q'){
return false;
}
colIndex--;
}
// left side
rowIndex = row;
colIndex = col;
while(rowIndex < n and colIndex >= 0){
if(board[rowIndex][colIndex] == 'Q'){
return false;
}
rowIndex++;
colIndex--;
}
return true;
}
void nQueens(vector<string> &board, int col, int n){
if(col == n){
ans.push_back(board);
for(int i = 0; i < n; i++){
cout<<board[i]<<", ";
}
cout<<endl;
return;
}
for(int row = 0; row < n; row++){
if(canPlace(board, row, col, n)){
cout<<"Changing board from: "<<board[row][col]<<endl;
board[row][col] = 'Q';
nQueens(board, col+1,n);
board[row][col] = '.';
}
}
}
vector<vector<string>> solveNQueens(int n) {
vector<string> board(n);
string s(n, '.');
for(int i = 0; i < n; i++){
board[i] = s;
// push_back gives weird result
}
nQueens(board, 0, n);
return ans;
}
};
在最后一个solveNQueens 函数中。在 for 循环中,如果我使用 board.push_back(s) 而不是 board[i] = s,leetcode 会抛出 Wrong Answer 错误,并且使用 cout 时的输出会显示奇怪的随机符号。
为什么是这样? push_back 不应该给出相同的结果吗?我很想知道为什么会这样。
这里是leetcode问题的链接:https://leetcode.com/problems/n-queens
【问题讨论】:
-
它们是不同的操作。你能解释一下为什么你期望他们给出同样的结果吗?
-
为什么你会期待同样的结果?
[]可让您修改现有元素,而push_back可追加新元素。 -
请将您的代码示例最小化为给定的问题/问题。为了解释访问向量的问题,没有人需要大量与您的问题完全无关的代码行。
标签: c++ recursion backtracking push-back n-queens