【发布时间】:2016-11-21 13:13:50
【问题描述】:
我正在练习这段代码(来自 LeetCode),以便在 C++ 中做得更好。不幸的是,我无法让“find”正常工作。
此代码用于从 char 类型的向量(即 board)中搜索 word,而无需两次访问同一个字母(visitedSoFar跟踪字母visitSoFar的x,y位置)。
Node 类的向量用于存储到目前为止访问过的位置。
这是我写的sn-p代码:
class Node{
private:
int x;
int y;
public:
Node(int a, int b):x(a),y(b){};
bool operator==(Node newNode){
if(this->x == newNode.x && this->y == newNode.y)
return true;
else
return false;
}
};
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
vector <Node> visitedSoFar;
for(int r =0; r< board.size(); r++){
for(int c=0; c<board[r].size(); c++){
if(board[r][c] == word.at(0)){
if(search(board, word, visitedSoFar, board[r].size(), r, c))
return true;
}
}
}
return false;
}
private:
bool search(vector<vector<char>>& board, string word, vector<Node>& visitedSoFar, int size, int r, int c){
Node newNode(r,c);
visitedSoFar.push_back(newNode);
if(word.size() == 1)
return true;
Node toSearch1(r-1,c);
if(r-1 >= 0 && find(visitedSoFar.begin(), visitedSoFar.end(), toSearch1) == visitedSoFar.end()){
if(board[r-1][c] == word.at(1))
if(search(board, word.substr(1), visitedSoFar, size, r-1, c))
return true;
}
Node toSearch2(r+1,c);
if(r+1 < size && find(visitedSoFar.begin(), visitedSoFar.end(), toSearch2) == visitedSoFar.end()){
if(board[r+1][c] == word.at(1))
if(search(board, word.substr(1), visitedSoFar, size, r+1, c))
return true;
}
Node toSearch3(r,c-1);
if(c-1 >= 0 && find(visitedSoFar.begin(), visitedSoFar.end(), toSearch3) == visitedSoFar.end()){
if(board[r][c-1] == word.at(1))
if(search(board, word.substr(1), visitedSoFar, size, r, c-1))
return true;
}
Node toSearch4(r,c+1);
if(c+1 < size && find(visitedSoFar.begin(), visitedSoFar.end(), toSearch4) == visitedSoFar.end()){
if(board[r][c+1] == word.at(1))
if(search(board, word.substr(1), visitedSoFar, size, r, c+1))
return true;
}
visitedSoFar.pop_back();
return false;
}
};
如果我对 find 发表评论,我会得到正确的输出,但这不适用于所有测试用例。
谢谢。
编辑
在方法搜索中,更正了 if 语句以检查 (r+1) 和 (c+1) 的大小。
编辑
单词可以由顺序相邻单元格的字母构成,其中“相邻”单元格是水平或垂直相邻的单元格。同一个字母单元格不能多次使用。
编辑
设计错误:查找操作应该无法找到(表明该节点到目前为止尚未访问过)然后继续在其中进行搜索。因此将 find 更改为 ==visitedSoFar.end() 而不是 !=visitedSoFar.end()。
【问题讨论】:
-
您没有给我们
main程序、您正在测试的数据或预期的输出。 -- 我正在练习这段代码(来自 LeetCode)以更好地使用 C++ -- 并且要“更好地使用 C++”需要你通过学习如何使用调试器来获得调试技能,而不仅仅是写个程序,希望能行,不行就去SO。 -
建议:
Solution类没有多大意义,它不存储任何状态。它的方法看起来几乎像 C 代码。我会将class更改为namespace,或者使board和visitedSoFar班级成员 -
您确定要检查 c+1 和 r+1 >=0 吗?不应该检查是否超过了电路板的尺寸?类似 c+1
-
@PaulMcKenzie 我来自 C 的背景,因此我的代码编写风格类似于 C。
-
@PrameetSinghKohli -- 我从未提到过
C编程,但更重要的是,您仍然没有提供minimal reproducible example,强调完成。
标签: c++ class vector stl iterator