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 =
[
['A','B','C','E'],
['S','F','C','S'],
['A','D','E','E']
]
word = "ABCCED"
, -> returns true
,
word = "SEE"
, -> returns true
,
word = "ABCB"
, -> returns false
.
简单的单词查找,在上下左右四个方向想dfs就可以了,代码如下,注意函数之间传递引用否则会超时的:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
if(!word.size())
return false;
int szHor = board.size();
if(!szHor) return false;
int szVer = board[].size();
if(!szVer) return false;
vector<vector<bool>> check(szHor, vector<bool>(szVer, false));
for(int i = ; i < szHor; ++i){
for(int j = ; j < szVer; ++j){
if(board[i][j] == word[]){
check[i][j] = true;
if(word.size() == || search(word.substr(), i, j, check, board))
return true;
check[i][j] = false;
}
}
}
return false;
} bool search(string word, int i, int j, vector<vector<bool>> & check, vector<vector<char>> & board)
{
vector<vector<char>> direction{{-, }, {, }, {, -}, {, }};
for(int k = ; k < ; ++k){
int ii = direction[k][] + i;
int jj = direction[k][] + j;
if(ii >= && ii < board.size() &&
jj >= && jj < board[].size() &&
board[ii][jj] == word[] &&
check[ii][jj] == false){
check[ii][jj] = true;
if(word.size() == || search(word.substr(), ii, jj, check, board))
return true;
check[ii][jj] = false;
}
}
return false;
}
};