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
.
解题思路:
使用深度优先搜索的方法,从二维数组中的每个点出发,向上下左右进行延伸,根据判定条件及时判断;
解题步骤:
1、写一个主函数:
(1)获得二维数组的行列大小;
(2)遍历所有二维数组元素,对每个元素作为搜索起点,调用递归函数;
2、写一个递归函数,参数为:二维数组(引用)、待匹配的字符串(c字符串形式方便)、当前运动到的坐标值x和y、二维数组大小m和n;
(1)终止判定条件:x和y无效、当前运动到的字符不是字符串下一个字符;
(2)如果已经到达匹配字符串末尾,返回true
(3)暂时将当前运动到的坐标字符置换为'\0',因为要做出标记,以免重复折返运动;
(4)调用4个递归函数,分别运动到当前运动字符的上下左右四周,并判定;
(5)如果4个递归函数都false,则换回被置换的'\0',返回false;
代码:
class Solution {
public:
bool exist(vector<vector<char> > &board, string word) {
m = board.size();
n = board[].size();
for(int x = ; x < m; x++) {
for(int y = ; y < n; y++) {
if(isFound(board, word.c_str(), x, y))
return true;
}
}
return false;
} private:
int m;
int n;
bool isFound(vector<vector<char> > &board, const char* w, int x, int y) {
if(x < || y < || x >= m || y >= n || *w != board[x][y])
return false;
if(*(w + ) == '\0')
return true;
char t = board[x][y];
board[x][y] = '\0';
if(isFound(board, w + , x - , y) ||
isFound(board, w + , x + , y) ||
isFound(board, w + , x, y - ) ||
isFound(board, w + , x, y + ))
return true;
board[x][y]=t;
return false;
}
};