字节跳动第一题

let M =10,N=10;
let matrix = [
    [0,0,0,0,0,0,0,0,0,0],
    [0,0,0,1,1,0,1,0,0,0],
    [0,1,0,0,0,0,0,1,0,1],
    [1,0,0,0,0,0,0,0,1,1],
    [0,0,0,1,1,1,0,0,0,1],
    [0,0,0,0,0,0,1,0,1,1],
    [0,1,1,0,0,0,0,0,0,0],
    [0,0,0,1,0,1,0,0,0,0],
    [0,0,1,0,0,1,0,0,0,0],
    [0,1,0,0,0,0,0,0,0,0]
];
let isPass = [];
for(let i = 0; i < M; i++ ){
    let tmp = [];
    for(let j = 0; j < N; j++){
        tmp[j] = false;
    }
    isPass.push(tmp);
}
let res = [];
for(let i = 0;i < M; i++){
    for(let j = 0; j < N; j++){
        let count = 0;
        if(matrix[i][j] == 1 && isPass[i][j] == false){
            count = traverse(matrix, isPass, i, j, count);
            res.push(count);
        }
    }
}
function traverse(matrix, isPass, x, y, count){
    if(x<0||x>=M||y<0||y>M){
        return 0;
    }
    if(matrix[x][y] == 1 && isPass[x][y] == false){
        isPass[x][y] = true;
        count++;
    }
    if(y - 1 >=0 && matrix[x][y-1] == 1 && isPass[x][y-1] == false){//1
        count = traverse(matrix,isPass,x,y-1,count);
    }
    if(x - 1 >=0 && matrix[x-1][y] == 1 && isPass[x-1][y] == false){//2
        count = traverse(matrix,isPass,x-1,y,count);
    }
    if(x - 1 >= 0 && y - 1 >= 0 && matrix[x-1][y-1] == 1 && isPass[x-1][y-1] == false){//3
        count = traverse(matrix,isPass,x-1,y-1,count);
    }
    if(x - 1 >= 0 && y + 1 < N && matrix[x-1][y+1] == 1 && isPass[x-1][y+1] == false){//4
        count = traverse(matrix,isPass,x-1,y+1,count);
    }
    if(y + 1 < N && matrix[x][y+1] == 1 && isPass[x][y+1] == false){//5
        count = traverse(matrix,isPass,x,y+1,count);
    }
    if(x + 1 < M && matrix[x+1][y] == 1 && isPass[x+1][y] == false) {//6
        count = traverse(matrix,isPass,x+1,y,count);
    }
    if(x + 1 <M && y + 1 <N && matrix[x+1][y+1] == 1 && isPass[x+1][y+1] == false){//7
        count = traverse(matrix,isPass,x+1,y+1,count);
    }
    if(x + 1 < M && y - 1 >= 0 && matrix[x+1][y-1] == 1 && isPass[x+1][y-1] == false){//8
        count = traverse(matrix,isPass,x+1,y-1,count);
    }
    return count;
}
console.log(res.length+","+Math.max(...res));

#笔试题目##字节跳动##题解#
全部评论
大佬,我想请问一下,怎么才能让自己的输入合法,每次我都死在写输入的方式上,不能写出符合题目规范的输入形式
点赞 回复 分享
发布于 2018-08-12 12:26
大佬,想问一下,第一题给的这个样例,我怎么感觉所有的0都是一个连通域?按照要求,那么队伍的个数不是1吗?
点赞 回复 分享
发布于 2018-08-12 12:52

相关推荐

耀孝女:就是你排序挂了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务