- 单词搜索
难度:中等
给定一个 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