
方法1: backtracking using dfs strategy to explore the grid。我觉得这是最好的描述这个算法的方法了。因为这其实是一个backtracking的算法,只是他是用dfs来explore整个grid的,整体思想还是backtracking。我代码里面backtracking体现在set.remove()那一行代码。时间复杂(mn)*(3^L),空间复杂L。复杂度分析如下:
这边我建议复盘的时候即使自己做出来了,也去看一遍lc官方解答,写的真的非常好,也不光是写得好,里面还有很多干货,一定要看。
class Solution {
public boolean exist(char[][] board, String word) {
Set<Pair<Integer,Integer>> set = new HashSet<>();
for(int i = 0; i < board.length; i++){
for(int j = 0; j < board[0].length; j++){
if(backtrack(board, i, j, 0, word, set)) return true;
}
}
return false;
}
public boolean backtrack(char[][] board, int i, int j, int n, String word, Set<Pair<Integer,Integer>> set){
if(set.contains(new Pair<>(i,j))) return false;
if(i < 0 || j < 0 || i >= board.length || j >= board[0].length || board[i][j] != word.charAt(n)) return false;
set.add(new Pair<>(i,j));
if(n == word.length() - 1) return true;
boolean b1 = backtrack(board, i-1, j, n+1, word, set);
boolean b2 = backtrack(board, i+1, j, n+1, word, set);
boolean b3 = backtrack(board, i, j-1, n+1, word, set);
boolean b4 = backtrack(board, i, j+1, n+1, word, set);
if((b1 || b2 || b3 || b4) == false){
set.remove(new Pair<Integer,Integer>(i,j));
return false;
}
return true;
}
}
总结:
- backtracking template :链接
这篇博客探讨了一种使用深度优先搜索(DFS)策略的回溯算法,用于在给定的二维网格中查找特定单词。作者通过详细讲解代码实现,解释了如何在网格中进行回溯搜索,并强调了在解决问题后复盘LC官方解答的重要性。该算法的时间复杂度为(mn)*(3^L),空间复杂度为L。
1113

被折叠的 条评论
为什么被折叠?



