[Algorithm] 44 week(11.28 ~ 12.04) 3/3

Dev_min·2022년 11월 30일
0

algorithm

목록 보기
143/157

200. Number of Islands

var numIslands = function(grid) {
    let count = 0;
    const list = grid.length;
    const wList = grid[0].length;


    function dfs(y, x) {
        if (grid[y][x] !== "1") return;

        grid[y][x] = "-1";

        if (y > 0) dfs(y - 1, x);
        if (y + 1 < list) dfs(y + 1, x);
        if (x > 0) dfs(y, x - 1);
        if (x + 1 < wList) dfs(y, x + 1);
    }

    for(let i = 0; i < list; i++){
        for(let j = 0; j < wList; j++){
            if(grid[i][j] === "1"){
                count += 1;
                dfs(i, j);
            }
        }
    }


    return count;
};
profile
TIL record

0개의 댓글