艾恩凝
个人博客 https://aeneag.xyz/
论文不想看,就多做道算法题吧,回溯深度搜索
欢迎关注微信公众号 “技术乱舞”
题目链接
https://leetcode-cn.com/problems/word-search/
分析
首先选择第一个字母匹配的,然后开始进行深度遍历,以该节点位置开始从上下左右延伸,直到找到适配所有的
题解
class Solution {
public:
bool exist(vector<vector<char>>& board, string word) {
int row = board.size(),col = board[0].size();
for(int i = 0 ; i < row ; ++i){
for(int j = 0 ; j < col ; ++j){
if(dfs(board,word,i,j,0,row,col))return true;
}
}
return false;
}
bool dfs(vector<vector<char>>& board, string word,int x,int y,int key,int row,int col){
if(board[x][y] != word[key])return false;
if(key == word.size()-1) return true;
vector<pair<int,int>> location = {{0,1},{0,-1},{1,0},{-1,0}};
char visited = board[x][y];
board[x][y] = '*';
for(auto & dir : location){
int dx = x + dir.first,dy = y + dir.second;
if(dx < 0 || dx >= row || dy < 0 || dy >= col || board[dx][dy]=='*')continue;
if(dfs(board,word,dx,dy,key+1,row,col))return true;
}
board[x][y] = visited;
return false;
}
};
欢迎关注公众号 “技术乱舞”
一起成长