码迷,mamicode.com
首页 > 其他好文 > 详细

[剑指offer] 矩阵中的路径

时间:2019-08-16 22:34:38      阅读:98      评论:0      收藏:0      [点我收藏+]

标签:标记   har   asp   href   length   return   uri   i++   off   

题目

https://www.acwing.com/problem/content/21/

思路

枚举。枚举起点,枚举四个方向。

时间复杂度:设矩阵n行m列,要匹配的字符串长k,O(nm*3^k)。

Java代码

class Solution {
    
    int[] dx = new int[]{-1, 0, 1, 0};
    int[] dy = new int[]{0, 1, 0, -1};
    
    public boolean hasPath(char[][] matrix, String str) {
        for(int i=0; i<matrix.length; i++)
            for(int j=0; j<matrix[0].length; j++){
                if(dfs(matrix, str, 0, i, j))
                    return true;
            }
        return false;        
    }
    
    private boolean dfs(char[][] matrix, String str, int k, int x, int y){
        char c = matrix[x][y];
        //if(k == str.length()) return true; 
        //if(matrix[x][y] != str.charAt(k)) return false; //注意这两行这样写不行,{{‘a’}}不能通过,因为不会进入下面的递归
        if(c != str.charAt(k)) return false;
        if(k == str.length()-1) return true;
        matrix[x][y] = '*';
        for(int i=0; i<4; i++){
            int a = x+dx[i], b = y+dy[i];
            if(a>=0 && a<matrix.length && b>=0 && b<matrix[0].length)
                if(dfs(matrix, str, k+1, a, b))
                    return true;
        }
        matrix[x][y] = c;
        return false;
    }
}

注意:在下一层递归之前,需要把当前字符做一个特殊标记(上述代码用*号代替),防止再次遍历;在结束递归之后,把当前字符还原。

参考

https://www.acwing.com/solution/AcWing/content/728/

[剑指offer] 矩阵中的路径

标签:标记   har   asp   href   length   return   uri   i++   off   

原文地址:https://www.cnblogs.com/sqqq/p/11366388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!