import java.util.*;


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param matrix char字符型二维数组 
     * @param word string字符串 
     * @return bool布尔型
     */
    public boolean hasPath (char[][] matrix, String word) {
        // write code here
        if(matrix == null || matrix.length == 0 || matrix[0].length == 0 || word == null || word.length() == 0){
            return false;
        }

        boolean flag = false;

        for(int i = 0; i < matrix.length; ++i){
            for(int j = 0; j < matrix[0].length; ++j){
                flag = isSubPath(matrix, word, i, j, 0);
                if(flag){
                    return flag;
                }
            }
        }

        return flag;
    }

    public boolean isSubPath(char[][] matrix, String word, int i, int j, int k){
        if(i < 0 || i >= matrix.length || j < 0 || j >= matrix[0].length || matrix[i][j] != word.charAt(k)){
            return false;
        }

        if(k == word.length() - 1 && word.charAt(k) == matrix[i][j]){
            return true;
        }

        matrix[i][j] = '\0';
        boolean res = isSubPath(matrix, word, i + 1, j, k + 1)
                   || isSubPath(matrix, word, i - 1, j, k + 1)
                   || isSubPath(matrix, word, i, j + 1, k + 1)
                   || isSubPath(matrix, word, i, j - 1, k + 1);
        matrix[i][j] = word.charAt(k);
        return res;
    }
}