• 【剑指Offer】12.矩阵中的路径


    题目

    请设计一个函数,用来判断在一个n乘m的矩阵中是否存在一条包含某长度为len的字符串所有字符的路径。路径可以从矩阵中的任意一个格子开始,每一步可以在矩阵中向左,向右,向上,向下移动一个格子。如果一条路径经过了矩阵中的某一个格子,则该路径不能再进入该格子。 例如 [[a,b,c,e],[s,f,c,s],[a,d,e,e]]​ 矩阵中包含一条字符串"bcced"的路径,但是矩阵中不包含"abcb"路径,因为字符串的第一个字符b占据了矩阵中的第一行第二个格子之后,路径不能再次进入该格子。

    数据范围:0≤n,m≤20 , 1≤len≤25 

    示例1

    输入:[[a,b,c,e],[s,f,c,s],[a,d,e,e]],"abcced"

    返回值:true

    示例2

    输入:[[a,b,c,e],[s,f,c,s],[a,d,e,e]],"abcb"

    返回值:false

    解答

    源代码

    1. import java.util.*;
    2. public class Solution {
    3. /**
    4. * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
    5. *
    6. *
    7. * @param matrix char字符型二维数组
    8. * @param word string字符串
    9. * @return bool布尔型
    10. */
    11. public boolean hasPath(char[][] matrix, String word) {
    12. // write code here
    13. for (int i = 0;i < matrix.length; i++) {
    14. for (int j = 0; j < matrix[0].length; j++) {
    15. if (dfs(matrix, word.toCharArray(), i, j, 0)) {
    16. return true;
    17. }
    18. }
    19. }
    20. return false;
    21. }
    22. public boolean dfs(char[][] matrix, char[] word, int i, int j, int index) {
    23. if (i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length || matrix[i][j] != word[index]) {
    24. return false;
    25. }
    26. if (index == word.length - 1) {
    27. return true;
    28. }
    29. char temp = matrix[i][j];
    30. matrix[i][j] = '.';
    31. boolean result = dfs(matrix, word, i - 1, j, index + 1) ||
    32. dfs(matrix, word, i + 1, j, index + 1) ||
    33. dfs(matrix, word, i, j - 1, index + 1) ||
    34. dfs(matrix, word, i, j + 1, index + 1);
    35. matrix[i][j] = temp;
    36. return result;
    37. }
    38. }

    总结

    递归回溯,越界或当前字符和所需的不等则返回false,否则判断当前是否为字符串的最后一个字符,是则返回true。最后进行递归,向当前字符的上下左右移动,回溯前将当前字符标记以防止重复经过,回溯结束之后将字符转换回来。

  • 相关阅读:
    PyTorch随机生成一个布尔型张量
    【算法面试题汇总】LeetBook列表的算法面试题汇总---树题目及答案
    hutool工具实践-缓存
    学习记录11
    基于springboot园区管理系统的设计与实现-计算机毕业设计源码+LW文档
    IDEA中如何移除未使用的import
    Corel VideoStudio会声会影2022旗舰版本视频剪辑软件
    龙芯电脑编译redis (loongarch)
    Kotlin第六弹:Kotlin方法与Lambda表达式
    消防大数据分析
  • 原文地址:https://blog.csdn.net/qq_57438473/article/details/133577491