剑指Offer-12:矩阵中的路径

题目描述:
给定一个 m x n 二维字符网格 board 和一个字符串单词 word 。如果 word 存在于网格中,返回 true ;否则,返回 false 。

单词必须按照字母顺序,通过相邻的单元格内的字母构成,其中“相邻”单元格是那些水平相邻或垂直相邻的单元格。同一个单元格内的字母不允许被重复使用。

例如,在下面的 3×4 的矩阵中包含单词 “ABCCED”(单词中的字母已标出)。
8
示例 1:

输入:board = [[“A”,“B”,“C”,“E”],[“S”,“F”,“C”,“S”],[“A”,“D”,“E”,“E”]], word = “ABCCED”
输出:true
示例 2:

输入:board = [[“a”,“b”],[“c”,“d”]], word = “abcd”
输出:false

提示:

1 <= board.length <= 200
1 <= board[i].length <= 200
board 和 word 仅由大小写英文字母组成

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/ju-zhen-zhong-de-lu-jing-lcof
思路1:本问题是典型的矩阵搜索问题,可使用 深度优先搜索(DFS)+ 剪枝 解决。
DFS三部曲
a.递归参数: 当前元素在矩阵 board 中的行列索引 row 和 col ,当前目标字符在 word 中的索引 pathLength 。
b.终止条件
返回true:pathLength=word.legth-1
返回false:越界或者当前元素不等于目标字符 以访问过的!
c.返回值
解答1:

public boolean exist(char[][] board, String word) {
        //特殊条件输入判断
        if (board == null || board.length == 0 || board[0].length == 0)
            return false;
        char[] str = word.toCharArray();
        int col = 0;
        int row = 0;
        int pathLength=0;
        for (row = 0; row < board.length; row++) {
            for (col = 0; col < board[0].length; col++) {
                if (hasPathCore(board, str, row, col, pathLength))
                    return true;
            }
        }
        return false;
    }

    public boolean hasPathCore(char[][] board, char[] word, int row, int col, int pathLength) {
     
        if (row >= board.length ||row<0 ||
                col >= board[0].length || col<0||
                board[row][col] != word[pathLength])//剪枝
            return false;
		   if (pathLength == word.length - 1)//全部匹配 终止条件
            return true;

        //从上边过来的说明 board[row][col]==word[pathLength]!!!
        //代表此元素已经访问过了 防止之后重复访问 
        board[row][col] = '\0';
        //分别从上下左右进行搜索
        boolean res = hasPathCore(board, word, row-1, col, pathLength+1)//上
        //pathLength+1 是向下一个字符出发
                || hasPathCore(board, word, row + 1, col, pathLength+1)//下
                || hasPathCore(board, word, row, col - 1, pathLength+1)//左
                || hasPathCore(board, word, row, col + 1, pathLength+1);//右
        //回溯
        board[row][col] = word[pathLength];
        //返回结果
        return res;
    }

部分答案参考与Leetcode!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值