题目:
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
.
题解:深度搜索 递归 308ms。程序运行时间总是超过time limit,最后压缩成如下才成功。
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
vector<vector<bool>> flag(board.size(), vector<bool>(board[0].size(), false));
for(size_t i = 0; i < board.size(); i++)
{
for(size_t j = 0; j < board[0].size(); j++)
{
if(board[i][j] == word[0] && dfs(flag, i, j, board, word, 0))
return true;
}
}
return false;
}
bool dfs(vector<vector<bool>> & flag, size_t x, size_t y, vector<vector<char> > &board, string word, size_t start)
{
if(start == word.length()) return true;
if(x < 0 || x >= board.size()) return false;
if(y < 0 || y >= board[0].size()) return false;
if(board[x][y] != word[start]) return false;
if(flag[x][y]) return false;
flag[x][y] = true;
bool result = dfs(flag, x+1, y, board, word, start+1) || dfs(flag, x-1, y, board, word, start+1) ||
dfs(flag, x, y+1, board, word, start+1) || dfs(flag, x, y-1, board, word, start+1);
flag[x][y] = false;
return result;
}
};