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
.
深度搜索,挨个搜索每个格子的四个角,符合条件就退出,这里的set<pair<int,int>>可以用vector<vector<int>>代替,会更快
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
if( word == "")
return true;
for( int i = 0; i < board.size(); ++i){
for( int j = 0; j < board[i].size(); ++j){
if( core(board, word, i, j))
return true;
}
}
return false;
}
bool core( vector< vector< char> > &board, string word, int i, int j){
if( word == "")
return true;
if( i < 0 || j < 0 || i >= board.size() || j >= board[i].size())
return false;
if( used.find( make_pair(i,j)) != used.end())
return false;
else{
if( board[i][j] == word[0]){
used.insert( make_pair(i,j));
bool res = core(board, word.substr(1), i+1, j) ||
core(board, word.substr(1), i, j+1) ||
core(board, word.substr(1), i-1, j) ||
core( board, word.substr(1), i, j-1);
used.erase( make_pair(i,j));
return res;
}
else{
return false;
}
}
}
private:
set< pair< int, int> > used;
};