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
.
思路:DFS题
int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
class Solution {
public:
void existHelper(vector<vector<bool>> &used, int curX, int curY, int pos,string &word,vector<vector<char>> &board,bool& res) {
if (res) {
return;
}
if (pos == word.length()) {
res = true;
return;
}
int i,j;
for (int d = 0; d < 4; ++d)
{
int nextX = curX+dir[d][0];
int nextY = curY+dir[d][1];
if(nextX >= 0 && nextX < board.size() && nextY >= 0 && nextY < board[0].size() && word[pos] == board[nextX][nextY])
{
if(!used[nextX][nextY])
{
used[nextX][nextY] = true;
existHelper(used,nextX,nextY,pos+1,word,board,res);
used[nextX][nextY] = false;
}
}
}
}
bool exist(vector<vector<char> > &board, string word) {
if (board.empty()) {
if (word.empty()) {
return true;
}
else {
return false;
}
}
vector<vector<bool> > used(board.size(),vector<bool>(board[0].size(), false));
int n = board.size();
int i,j,pos=0;
bool res = false;
for(i=0; i<board.size(); ++i) {
for(j=0; j<board[i].size(); ++j) {
if (board[i][j] == word[pos]) {
used[i][j] = true;
existHelper(used,i,j,pos+1,word,board,res);
used[i][j] = false;
}
if (res) {
return res;
}
}
}
return res;
}
};