leetcode_word_search

难度:Medium

解题思路:深度优先遍历。如果某个字符串匹配,则对它的上、下、左、右分别进行递归,同时将匹配的字符串辨识成”*”,防止重复,递归好之后,要记得还原。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
bool ret;
for(int i = 0; i < board.size(); i++)
{
for(int j = 0; j < board[0].size(); j++)
{
ret = search_char(board,i,j,word,0);
if(ret ==true)
return ret;
}
}
return false;
}
bool search_char(vector<vector<char>>& board, int i, int j, string word, int word_index)
{
if(i < 0 || i >= board.size())
return false;
if(j < 0 || j >= board[0].size())
return false;
// cout<<"find: "<<board[i][j]<<endl;
if(word[word_index] != board[i][j])
{
return false;
}
else
{
char ch = board[i][j];
board[i][j] = '$';
bool ret = true;
if(word_index+1 == word.size())
return ret;
ret = ret && search_char(board, i-1,j,word,word_index+1);
if(ret == true)
return true;
ret = true;
ret = ret && search_char(board, i+1,j,word,word_index+1);
if(ret == true)
return true;
ret = true;
ret = ret && search_char(board, i,j-1,word,word_index+1);
if(ret == true)
return true;
ret = true;
ret = ret && search_char(board, i,j+1,word,word_index+1);
board[i][j] = ch;
return ret;
}
}
};

运行结果:56ms,超过34.01%