矩阵中的路径-DFS(利用递归特性实现DFS的回溯)

矩阵中的路径

http://www.nowcoder.com/questionTerminal/2a49359695a544b8939c77358d29b7e6

public boolean hasPath (char[][] matrix, String word) {
    int rows = matrix.length;
    if (rows == 0) return false;
    int cols = matrix[0].length;
    boolean[][] visited = new boolean[rows][cols];//标识每个方格是否在路径里面,防止路径进入重复的方格里
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            if (hasPath (matrix,i,j,visited,word,0)) return true;
        }
    }
    return false;
}

public boolean hasPath (char[][] matrix,int row,int col,boolean[][] visited,String word,int loc) {
    if (loc == word.length()) return true;
    int rows = matrix.length;
    int cols = matrix[0].length;
    if (row < 0 || row == rows || col < 0 || col == cols) return false;
    if (visited[row][col]) return false;
    if (matrix[row][col] == word.charAt(loc)){
        visited[row][col] = true;
        if (hasPath (matrix,row-1,col,visited,word,loc+1) || hasPath (matrix,row+1,col,visited,word,loc+1)
        || hasPath (matrix,row,col-1,visited,word,loc+1) || hasPath (matrix,row,col+1,visited,word,loc+1)){
            return true;
        }
        visited[row][col] = false;
    }
    return false;
}
全部评论

相关推荐

吐泡泡的咸鱼:我也工作了几年了,也陆陆续续面试过不少人,就简历来说,第一眼学历不太够,你只能靠你的实习或者论文或者项目经历,然后你没有论文,没有含金量高的比赛和奖项,只能看实习和项目,实习来说,你写的实习经历完全不清楚你想找什么工作?行研?数据分析?且写的太少了,再看项目,这些项目先不说上过大学读过研究生的都知道很水,然后对你想找的岗位有什么帮助呢?项目和实习也完全不匹配啊,你好像在努力将你所有的经历都放在简历里想表现你的优秀,但是对于你想找的岗位来说,有什么用呢?最后只能获得岗位不匹配的评价。所以你需要明白你想要找的岗位要求是什么,是做什么的,比如产品经理,然后再看你的经历里有什么匹配的上这个岗位,或者对这个岗位以及这个岗位所在的公司有价值,再写到你的简历上
点赞 评论 收藏
分享
评论
5
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务