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-02 16:49
门头沟学院 Java
_bloodstream_:我也面了科大讯飞,主管面的时候听说急招人优先考虑能尽快实习的,我说忙毕设,后面就一直没消息了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务