题目链接:79. 单词搜索 - 力扣(LeetCode)
要在一个二维数组里面找到一条单词路径,可以先遍历二维数组找到单词入口,然后往上下左右深度遍历,访问过的元素直接修改成字符串结束符,访问完改回去
class Solution {
public:
string word;
int row, column;
vector<vector<char> > board;
bool dfs(int i, int j, int count) {
if (i >= row || j >= column || i < 0 || j < 0 || board[i][j] != word[count])
return false;
if (count == word.size() - 1)
return true;
board[i][j] = '\0';
++count;
bool next = dfs(i - 1, j, count) || dfs(i, j - 1, count) || dfs(i + 1, j, count) || dfs(i, j + 1, count);
board[i][j] = word[--count];
return next;
}
bool exist(vector<vector<char> > &board, string word) {
this->board = move(board);
this->word = move(word);
row = this->board.size();
column = this->board[0].size();
for (int i = 0; i < row; ++i)
for (int j = 0; j < column; ++j) {
if (dfs(i, j, 0))
return true;
}
return false;
}
};