我正在练习这段代码(来自LeetCode),以便更好地掌握C ++。不幸的是,我无法正确使用“find”。此代码用于在类型为char的vector的vector(即board)中搜索word,而不访问相同的字母(visitedSoFar跟踪已访问字母的x,y位置)。一个存储到目前为止访问位置的Node类向量被用来存储位置。
这是我编写的代码片段:
如果我注释掉find,我会得到正确的输出,但这对于所有测试用例都不起作用。
谢谢。
编辑 在search方法中,修正了if语句以检查(r+1)和(c+1)的大小。
编辑 单词可以由相邻单元格的字母构成,其中“相邻”单元格是水平或垂直相邻的单元格。不能重复使用同一字母单元格。
编辑 设计错误:find操作不应该能够找到(表明节点到目前为止还没有被访问),然后在其中进行搜索。因此,将find更改为== visitedSoFar.end()而不是!= visitedSoFar.end()。
这是我编写的代码片段:
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,我会得到正确的输出,但这对于所有测试用例都不起作用。
谢谢。
编辑 在search方法中,修正了if语句以检查(r+1)和(c+1)的大小。
编辑 单词可以由相邻单元格的字母构成,其中“相邻”单元格是水平或垂直相邻的单元格。不能重复使用同一字母单元格。
编辑 设计错误:find操作不应该能够找到(表明节点到目前为止还没有被访问),然后在其中进行搜索。因此,将find更改为== visitedSoFar.end()而不是!= visitedSoFar.end()。
main
程序,也没有测试数据或期望输出。-- 我正在练习这段来自 LeetCode 的代码,以更好地掌握 C++ -- 而要 “更好地掌握 C++”,就需要学习如何使用调试器,获得调试技能,而不仅仅是编写程序,希望它能正常运行,如果不能正常工作,就去 SO 上寻求帮助。 - PaulMcKenzieSolution
类没有太多意义,它不存储状态。它的方法看起来几乎像 C 代码。我会将class
更改为namespace
,或者将board
和visitedSoFar
设为类成员。 - xinaizC
编程,但更重要的是,你仍然没有提供一个完整的[mcve],强调完整。 - PaulMcKenzie