给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
例如,在下面的 3×4 的矩阵中包含单词 "ABCCED"(单词中的字母已标出)。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
示例 2:
输入:board = [["a","b"],["c","d"]], word = "abcd"
输出:false
提示:
1 <= board.length <= 200
1 <= board[i].length <= 200
board 和 word 仅由大小写英文字母组成
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
for(int i = 0; i < board.size(); i++)
for(int j = 0; j < board[i].size(); j++)
//遍历所有开始位置
if(dfs(board,word,0,i,j)) return true;
return false;
}
//u表示长度,X,y表示开始查找位置
bool dfs(vector<vector<char>>& board,string &word,int u,int x,int y){
//当第一个字符不匹配时,返回false
if(board[x][y] != word[u]) return false;
//找到该字符,且长度相等
if(u == word.size() - 1) return true;
//查找方向
int dx[4] = {-1,0,1,0},dy[4] = {0,1,0,-1};
char t = board[x][y];
board[x][y] = '*';
//向四个方向进行查找
for(int i = 0; i < 4; i++){
int a = dx[i] + x,b = dy[i] + y;
//边间判断
if(a >= 0 && a < board.size() && b >= 0 && b < board[a].size()){
//递归查找
if(dfs(board,word,u + 1,a,b)) return true;
}
}
//回溯
board[x][y] = t;
return false;
}
};