方法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 :链接