// 经典dfs题型(一个简单的dfs写了我那么久,果然老了,不中用了...)

public class Solution {

    private final int dx[] = {1, -1, 0, 0}; 
    private final int dy[] = {0, 0, 1, -1};

    public boolean jude(char[] matrix, int rows, int cols, char[] str, int k, int index, boolean[] vis) {

        vis[index] = true;
        if (k == str.length) { // 匹配成功
            return true;
        }

        int x = index / cols;
        int y = index % cols;

        for (int i = 0; i < 4; i++) { // 向四个方向走
            int X = x + dx[i];
            int Y = y + dy[i];
            int next = X * cols + Y;
            if (X >= 0 && Y >= 0 && X < rows && Y < cols && !vis[next] && matrix[next] == str[k] && jude(matrix, rows, cols, str, k + 1, next, vis)) {
                return true;
            }

        }
        vis[index] = false;
        return false;
    }

    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        if (matrix == null || str == null || rows < 1 || cols < 1) {
            return false;
        }
        boolean[] vis = new boolean[matrix.length]; // 标记数组
        for (int i = 0; i < matrix.length; i++) {
            if (matrix[i] == str[0] && jude(matrix, rows, cols, str, 1, i, vis)) {
                return true;
            }
        }
        return false;
    }
}