题解 | #矩阵中的路径#

矩阵中的路径

http://www.nowcoder.com/practice/2a49359695a544b8939c77358d29b7e6

进行DFS遍历,每次到一个位置先判断是否能匹配word中的一个,能才踩下去

    int[][] dirs = {{0,-1},{0,1},{-1,0},{1,0}};//左,右,上,下
    public boolean hasPath (char[][] matrix, String word) {
        //思路:遍历数组,从随意row,col出发,去过的位置用一个boolean二维数组进行标记
        if(matrix==null||matrix.length==0) return false;
        //每一步都进行判断,相同才尝试去走
        int rows = matrix.length;
        int cols = matrix[0].length;
        char[] words = word.toCharArray();
        boolean[][] isCame = new boolean[rows][cols];//标记一个位置是否走过
        for(int row = 0;row<rows;row++){
            for(int col = 0;col<cols;col++){
                if(canGetWord(matrix,words,0,row,col,isCame,rows,cols)){
                    return true;
                }
            }
        }
        return false;
    }
    //来到row,col位置,还没踩下去
    public boolean canGetWord(char[][] matrix,char[] words,
                              int idx,int row,int col,
                              boolean[][] isCame,int rows,int cols){
        if(idx==words.length) return true;
        if(row<0||row>=rows||col<0||col>=cols||matrix[row][col]!=words[idx]||isCame[row][col]) return false;
        //尝试往四个方向走
        boolean res = false;
        for(int[] dir:dirs){
            isCame[row][col] = true;//踩下去
            if(canGetWord(matrix,words,idx+1,row+dir[0],col+dir[1],isCame,rows,cols)){
                res = true;
            }
            isCame[row][col] = false;//轨迹擦除
        }
        return res;
    }
waigo的刷题之路 文章被收录于专栏

收录平时刷题的题解

全部评论

相关推荐

找个工作&nbsp;学历是要卡的&nbsp;要求是高的&nbsp;技能不足是真的&nbsp;实习经验是0的&nbsp;简历无处可写是事实的&nbsp;钱不好赚是真的&nbsp;想躺平又不敢躺&nbsp;也不甘心躺&nbsp;怕自己的灵感和才华被掩埋甚至从未被自己发现&nbsp;又质疑自己是否真正有才华
码农索隆:你现在啊,你心里都明白咋回事,但是你没办法改变现状,一想到未来,你又没有信心狠下心来在当下努力。 得走出这种状态,不能一直困在那里面,哪不行就去提升哪,你一动不动那指定改变不了未来,动起来,积少成多才能越来越好
点赞 评论 收藏
分享
积极的小学生不要香菜:你才沟通多少,没500不要说难
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务