코테

[leetcode] 1254. Number of Closed Islands

테오구 2022. 6. 4. 22:21
728x90

https://leetcode.com/problems/number-of-closed-islands/

 

Number of Closed Islands - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

입출력 예제

풀이

0이 육지이고 1이 바다이다.

Return the number of closed islands.

즉 1(바다)로 둘러싸인 0(유지)의 수를 반환해야하는 것이다.

 

나의 풀이 방법은 이러했다.

이중배열을 돌면서 섬의 개수를 모두 센 후 그 중 보드판을 넘어가는 경우를 뺴주었다.

 

var closedIsland = function(grid) {
    const dx = [0,0,-1,1]
    const dy = [-1,1,0,0]
    const M = grid.length
    const N = grid[0].length
    const isVisited = Array.from(Array(M), () => new Array(N).fill(false))
    const isValid = (row, col) => row >= 0 && row < M && col >= 0 && col < N;
    let check = false
    let numOfLand = 0
    let cnt = 0

    for(let j = 0; j < M; j++){
        for(let k = 0; k < N; k++){
            if(grid[j][k] === 0 &&!isVisited[j][k]){
                floodfill(j,k)
                if(check){
                    cnt++
                    check = false

                }
                numOfLand++
            }
        }
    }
    
    function floodfill(j,k){
        if(!isValid(j,k)){
            check = true
        }

        if(isValid(j,k) &&      !isVisited[j][k] && grid[j][k] === 0){
            isVisited[j][k] = true
            for(let i = 0; i < dx.length; i++){
                const nx = j + dx[i]
                const ny = k + dy[i]
                floodfill(nx, ny)
            }
        }
    }

    return numOfLand - cnt
};
728x90

'코테' 카테고리의 다른 글

큰 수 만들기  (0) 2022.06.13
[LeetCode] 617. Merge Two Binary Trees  (0) 2022.06.06
[leetCode] 695. Max Area of Island  (0) 2022.06.02
애니어그램  (0) 2022.05.16
짝지어 제거하기  (0) 2022.05.14