给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。
单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。
示例 1:
输入:board = [["A","B","C","E"],["S","F","C","S"],["A","D","E","E"]], word = "ABCCED"
输出:true
思路:
和岛屿的思路基本相同,只不过这里在进入递归之前进行剪枝,减少了栈的空间消耗
class Solution {
public:
bool dfs(vector<vector<char>>& board,int i,int j,string word,int start){
if( board[i][j] != word[start]) return false;
if(start == word.size() - 1) return true;
char c =board[i][j];
board[i][j] = '.';
for(int index = 0; index < 4; ++index){
int next_i = i + di[index];
int next_j = j + dj[index];
if(next_i < 0 || next_j < 0 || next_i >= board.size() || next_j >= board[0].size()) continue;
if(dfs(board, next_i,next_j,word,start+1)) return true;
}
board[i][j] = c;
return false;
}
bool exist(vector<vector<char>>& board, string word) {
int count = 0;
//遍历board 如果符合 则进入dfs的下一层
for(int i = 0;i < board.size();i++){
for(int j = 0; j < board[i].size();j++){
if(dfs(board,i,j,word,0)){
return true;
}
}
}
return false;
}
private:
int di[4] = {-1,0,1,0};
int dj[4] = {0,1,0,-1};
};
标签:index,word,int,next,单词,搜索,board,return,79
From: https://www.cnblogs.com/lihaoxiang/p/17735565.html