题目:
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.
题意:
给定一个二维的字符数组,查找某个单词是否在里面出现。单词可以由数组中相邻的字符组成,相邻的字符即指上下左右这四种相对位置的字符。
思路:
这道题目是个明显的回溯的题目,或者可以称为深度优先的遍历。以某个字符作为开始查找的字符,如果该字符与字符串的第一个字符一样,那就递归去查找该字符的相邻的节点是否与字符串的下一个节点一样。我们可以将查过的字符改变为某种特殊的字符,比如’*’,然后回溯回来的时候再将其改为原来的字符。如果在其四个方向能够匹配出剩下的字符串部分,那么久返回true,否则返回false。字符串的开始位置可能是字符串数组的任何一个位置,所以需要查看以任一个位置作为起点的字符串查找的结果。
以上。
代码如下:
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int m = board.size();
if (m == 0)return false;
int n = board[0].size();
if (m*n < word.length())return false;
this->m = m;
this->n = n;
this->board = board;
this->word = word;
for (int i = 0; i < m; i++)
for (int j = 0; j < n; j++) {
if (exist(i, j, 0))return true;
}
return false;
}
bool exist(int i, int j, int index) {
if (index == word.length())
return true;
if (i < 0 || j < 0 || i >= m || j >= n)return false;
char temp = board[i][j];
board[i][j] = '*';
if (temp == word[index]) {
bool result = exist(i + 1, j, index + 1) ||
exist(i - 1, j, index + 1) ||
exist(i, j + 1, index + 1) ||
exist(i, j - 1, index + 1);
board[i][j] = temp;
return result;
}
board[i][j] = temp;
return false;
}
private:
vector<vector<char>> board;
int m;
int n;
string word;
};