JZ65-矩阵中的路径

矩阵中的路径

https://www.nowcoder.com/practice/69fe7a584f0a445da1b6652978de5c38?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey

class Solution {
    boolean[] visited = null;

    public boolean hasPath(char[] matrix, int rows, int cols, char[] str) {
        visited = new boolean[matrix.length];
        for (int i = 0; i < rows; i++)
            for (int j = 0; j < cols; j++)
                if (subHasPath(matrix, rows, cols, str, i, j, 0))
                    return true;
        return false;
    }

    public boolean subHasPath(char[] matrix, int rows, int cols, char[] str, int row, int col, int len) {
        if (matrix[row * cols + col] != str[len] || visited[row * cols + col] == true) return false;
        if (len == str.length - 1) return true;
        visited[row * cols + col] = true;
        if (row > 0 && subHasPath(matrix, rows, cols, str, row - 1, col, len + 1)) return true;
        if (row < rows - 1 && subHasPath(matrix, rows, cols, str, row + 1, col, len + 1)) return true;
        if (col > 0 && subHasPath(matrix, rows, cols, str, row, col - 1, len + 1)) return true;
        if (col < cols - 1 && subHasPath(matrix, rows, cols, str, row, col + 1, len + 1)) return true;
        visited[row * cols + col] = false;
        return false;
    }
}

全部评论

相关推荐

04-11 15:34
已编辑
华中科技大学 网络安全
疯犬丨哈士奇:意思就是:我们还有其他更优秀的人在等回复,如果他们不要这个机会就会来找你
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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