Given a 2D board and a word, find if the word exists in the grid.
The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED",
-> returns true,word =
"SEE",
-> returns true,word = "ABCB",
-> returns false.
class Solution {
public:
bool dfs(int depth,vector<vector<char> >&board,string word,int x,int y){
if(depth==word.size())
{
return true;
}
else if(x>=board.size()||x<0)return false;
else if(y>=board[0].size()||y<0)return false;
else
{
if(board[x][y]==word[depth])
{
board[x][y]='.';
if(dfs(depth+1,board,word,x+1,y))return true;
if(dfs(depth+1,board,word,x,y+1))return true;
if(dfs(depth+1,board,word,x-1,y))return true;
if(dfs(depth+1,board,word,x,y-1))return true;
board[x][y]=word[depth];
return false;
}
else
return false;
}
}
bool exist(vector<vector<char> > &board, string word) {
bool f=false;
if(board.size()==0)return false;
if(board[0].size()==0)return true;
for(int i=0;i<board.size();++i)
for(int j=0;j<board[0].size();++j)
{
if(dfs(0,board,word,i,j))
f=true;
}
//if(f==true)cout<<"true"<<endl;
//else std::cout << "false" << std::endl;
return f;
}
};
本文介绍了一个算法,用于在二维字符网格中查找指定单词是否存在。通过深度优先搜索(DFS)策略,该算法遍历网格,检查每个单元格是否能构成目标单词,并确保同一单元格不被重复使用。
977

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



