题解 | #矩阵中的路径#

矩阵中的路径

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

import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param matrix char字符型二维数组 
     * @param word string字符串 
     * @return bool布尔型
     */
    public boolean hasPath (char[][] matrix, String word) {
        // write code here
        //判断二维字符数组是否包含某条路径
        //路径要与字母一一匹配,但不能往回走,
        //可以先找到包含首字母的元素.
        //方法是递归,向外找,某一个阶段不符合,就可以直接返回false,到最后,true
        if(matrix.length == 0){
            return false;
        }
        int index = 0;
        //找到首元素
        for(int i = 0; i < matrix.length; i++){
            for(int j = 0; j < matrix[0].length; j++){
                if(justy(matrix,word,i,j,index)){
                    return true;
                }
            }
        }
        return false;
    }
    public static boolean justy(char[][] matrix, String word, int x, int y, int index){
        //遇到边界值,小于0,或者大于数组长度,或者不符合要求,返回false
        if(x < 0 || y < 0 || x >= matrix.length|| y >= matrix[0].length || matrix[x][y] != word.charAt(index) ){
            return false;
        }
        //可以举一个例子,长度位为1,未返回false,首字母相等,返回true
        if(index == word.length()-1){
            return true;
        }
        char tmp = matrix[x][y];
        matrix[x][y] = '#';
        boolean b =  justy(matrix,word,x-1,y,index+1) || justy(matrix,word,x,y+1,index+1) || justy(matrix,word,x,y-1,index+1) || justy(matrix,word,x+1,y,index+1);
        matrix[x][y] = tmp;
        return b;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务