- 单词搜索
难度:中等
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
class Solution {
public:
bool fun(vector<vector<char>>& board,vector<vector<bool>>& mark, int x,int y,string word,int index)
{
if(word.size() == index)return true;
if(x>=board.size() || y >= board[0].size())return false;
if(x<0 || y<0)return false;
if(mark[x][y]==true)return false;
if(board[x][y] != word[index])return false;
//右
bool is;
mark[x][y] = true;
if(fun(board,mark,x,y+1,word,index+1) || fun(board,mark,x+1,y,word,index+1)
|| fun(board,mark,x,y-1,word,index+1) || fun(board,mark,x-1,y,word,index+1))
return true;
mark[x][y] = false;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int x = board.size();
int y = board[0].size();
vector<vector<bool>> v(x,vector<bool>(y));
for(int i = 0;i< x;i++)
{
for(int j=0;j<y;j++)
{
if(fun(board,v,i,j,word,0))
return true;
}
}
return false;
}
};
执行结果:
通过
显示详情
添加备注
执行用时:
560 ms, 在所有 C++ 提交中击败了29.82%的用户
内存消耗:
7.8 MB, 在所有 C++ 提交中击败了38.33%的用户
通过测试用例:
82 / 82
这篇博客讨论了一个C++实现的算法,用于在给定的二维字符网格中查找给定单词是否存在。算法采用深度优先搜索(DFS)策略,检查单词是否按照字母顺序通过相邻单元格构成,并且不重复使用同一单元格。代码中定义了一个`fun`函数进行递归搜索,并在`exist`函数中遍历整个网格进行查找。该算法的时间复杂度和空间复杂度较高,适用于中等难度的单词搜索问题。
402

被折叠的 条评论
为什么被折叠?



