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)暂时将当前运动到的坐标字符置换为' ',因为要做出标记,以免重复折返运动;
(4)调用4个递归函数,分别运动到当前运动字符的上下左右四周,并判定;
(5)如果4个递归函数都false,则换回被置换的' ',返回false;
代码:
1 class Solution { 2 public: 3 bool exist(vector<vector<char> > &board, string word) { 4 m = board.size(); 5 n = board[0].size(); 6 for(int x = 0; x < m; x++) { 7 for(int y = 0; y < n; y++) { 8 if(isFound(board, word.c_str(), x, y)) 9 return true; 10 } 11 } 12 return false; 13 } 14 15 private: 16 int m; 17 int n; 18 bool isFound(vector<vector<char> > &board, const char* w, int x, int y) { 19 if(x < 0 || y < 0 || x >= m || y >= n || *w != board[x][y]) 20 return false; 21 if(*(w + 1) == '