题目:
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.
给定一个2维板和一个单词,确定在这个板中是否存在这个单词。
单词可以由连续相邻单元的字母组成。相邻单元指的是上下左右相邻。相同的字母不能使用超过一次。
For example,
Given board =
[ ["ABCE"], ["SFCS"], ["ADEE"] ]word =
"ABCCED"
, -> returns
true
,
word =
"SEE"
, -> returns
true
,
word =
"ABCB"
, -> returns
false
.
思路:
基本思路就是从某一个元素出发,往上下左右进行深度搜索。判断是否有等于word的字符串。这里因为要求相同的字母不能使用超过一次,因此需要用个bool型变量标记当前字母是否被标记过。
代码:
class Solution {
public:
bool exist(vector<vector<char> > &board, string word)
{
if(board.empty())
return false;
int row = board.size();
int col = board[0].size();
vector<vector<bool> > visited(row,vector<bool>(col,false));//标记深搜时当前字母是否判断过
for(int i = 0 ; i < row ; i++)
{
for(int j = 0 ; j < col ; j++)
{
//从当前点board[i][j开始进行深搜
if(dfs(board,word,0,i,j,visited))
return true;
}
}
return false;
}
bool dfs(vector<vector<char> > &board, string &word,int index,int i , int j,vector<vector<bool> > &visited)
{
//index到达word最后,说明找到了符合的
if(index == word.size())
return true;
if(i<0 || j<0 || i>=board.size() || j>= board[0].size())
return false;
//如果当前字母被访问过
if(visited[i][j])
return false;
//当前字母不符合条件
if(word[index] != board[i][j])
return false;
//以上都不满足,说明当前字母符合条件,置为true,继续对当前单词的上下左右深搜
visited[i][j] = true;
bool ret = dfs(board,word,index+1,i-1,j,visited) ||
dfs(board,word,index+1,i+1,j,visited) ||
dfs(board,word,index+1,i,j-1,visited) ||
dfs(board,word,index+1,i,j+1,visited);
//从board[i][j]点开始深搜完成后,visited要重置为false
visited[i][j] = false;
return ret;
}
};