问题:
Given a 2D board and a word, find if the word exists in the grid.
word =
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深度优先搜索。
可是,超时了。可是,想不到别的办法了啊。。智能的算法又不会。。。
人品差啊,为什么会超时呢?
我改进!
1、为了记录某位置已经访问过,直接换成'#'就行了。这样省去申请临时空间。
2、递归不要传入子串,直接传入字符串下标。
还是不行!怎么回事!
我检查!
原来,我边界条件写错了,少了一个等于的情况1。。。。太大意了了。边界条件是最重要的。
class Solution {
public:
bool dfs(vector<vector<char> > &board, int i, int j, string &s, int index)
{
if(index == s.size())
return true;
if(i>=1 && board[i-1][j] == s[index])
{
board[i-1][j] = '#';
if(dfs(board, i-1, j, s, index+1) )
return true;
board[i-1][j] = s[index];
}
if(i+1<board.size() && board[i+1][j] == s[index])
{
board[i+1][j] = '#';
if(dfs(board, i+1, j, s, index+1) )
return true;
board[i+1][j] = s[index];
}
if(j>=1 && board[i][j-1] == s[index])
{
board[i][j-1] = '#';
if(dfs(board, i, j-1, s, index+1))
return true;
board[i][j-1] = s[index];
}
if(j+1<board[0].size() && board[i][j+1] == s[index])
{
board[i][j+1] = '#';
if(dfs(board, i, j+1, s, index+1))
return true;
board[i][j+1] = s[index];
}
return false;
}
bool exist(vector<vector<char> > &board, string word) {
int row = board.size();
if(row == 0)
return false;
int col = board[0].size();
for(int i=0;i<row;i++)
for(int j=0;j<col;j++)
{
if(board[i][j] == word[0])
{
board[i][j] = '#';
if( dfs(board, i, j, word, 1) )
return true;
board[i][j] = word[0];
}
}
return false;
}
};