LeetCode79. 单词搜索(剑指 Offer 12. 矩阵中的路径)-DFS

1题目

2思路

经典的DFS题

题目中字符串的长度为为K,主站中K的最大为15

表格中大小为M * N ,主站中MN最大为6 * 6

时间复杂度为:3^K * M * N == 1 * 10^7 * 36 = 3.6 * 10^8 .看起来会超时,但是由于中途存在剪枝情况,比如已经访问过,就不再访问;值不相等,就不再访问,所以最终的时间复杂度会远远小于这个数。

1.找到dfs入口

2.定义边界条件

3.定义是否访问的数组,有时候也是直接在原数组上进行改动。

4.dfs上下左右四个方向。

5.注意回溯,让标记跟一开始进来的时候保持一致。

为什么要回溯?

因为存在这样的情况, A 和B , A 和 C 都相连, D和 B ,D 和C都相连,当dfs从A 开始时候,访问下面的C,假如没找到答案,但是这时候这个下面的C已经被标记已访问,当A从右边的B,再到D时候,这时候按理说还可以继续访问左边的C,但是由于一开始的时候没有回溯,导致这个左边的C 不能访问,所以就无法形成ABDC。所以一定要记得回溯。回溯的目的就代表这个数还可以继续被访问。

A -- B       
C -- D

class Solution {
    int n , m ;
    int[][]vis;
    int cnt = 0;
    public boolean exist(char[][] board, String word) {
        n = board.length;
        m = board[0].length;
        cnt = word.length();
        for(int  i = 0 ; i < n; i++){
            for(int j = 0 ; j < m; j++){
                if(board[i][j] == word.charAt(0)){
                    vis = new int[n][m];
                    if(dfs(i, j, 0, board, word))return true;
                }
            }
        }
        return false;
    }

    public boolean dfs(int x, int y, int index, char[][]board, String word){
        // if(index == cnt - 1) return true;
        // int[][]dirs = new int[][]{{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
        // vis[x][y] = 1;
        // for(int[]dir : dirs){
        //     int dx = dir[0], dy = dir[1];
        //     int nx = x + dx, ny = y + dy;
        //     if(nx < 0 || nx >= n || ny < 0 || ny >= m || board[nx][ny] != word.charAt(index  + 1) || vis[nx][ny] == 1) continue;
        //     if(dfs(nx, ny, index + 1, board, word)) return true;
        // }
        // vis[x][y] = 0; // 记得回溯,标记为未访问
        if(x < 0 || x >= n || y < 0 || y >= m || board[x][y] != word.charAt(index) || vis[x][y] == 1) return  false;
        if(index == cnt - 1)return true;
        vis[x][y] = 1;
        boolean res = dfs(x, y + 1, index + 1, board, word) || dfs(x, y - 1, index + 1, board, word) || dfs(x + 1, y, index + 1, board, word) || dfs(x - 1, y, index + 1, board, word);
        vis[x][y] = 0; //回溯很重要!!!
        return res;
    }
}

3结果

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值