Leetcode 79. Word Search

这篇博客探讨了一种使用深度优先搜索(DFS)策略的回溯算法,用于在给定的二维网格中查找特定单词。作者通过详细讲解代码实现,解释了如何在网格中进行回溯搜索,并强调了在解决问题后复盘LC官方解答的重要性。该算法的时间复杂度为(mn)*(3^L),空间复杂度为L。
摘要由CSDN通过智能技术生成

在这里插入图片描述
方法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 :链接
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值