[TIL] DFS 문제 풀이 / 왓챠피디아 클론코딩 프로젝트

김정호·2022년 2월 19일

자바스크립트 코딩테스트

백준 4963 섬의 개수
https://www.acmicpc.net/problem/4963

function dfsIsland(h, w, height, width, seaMap) {
    if (h < 0 || h >= height || w < 0 || w >= width) return
    if (seaMap[h][w] === 1) {
        seaMap[h][w] = 0
        dfsIsland(h, w + 1, height, width, seaMap)
        dfsIsland(h, w - 1, height, width, seaMap)
        dfsIsland(h - 1, w, height, width, seaMap)
        dfsIsland(h - 1, w - 1, height, width, seaMap)
        dfsIsland(h - 1, w + 1, height, width, seaMap)
        dfsIsland(h + 1, w , height, width, seaMap)
        dfsIsland(h + 1, w - 1, height, width, seaMap)
        dfsIsland(h + 1, w + 1, height, width, seaMap)
    }
}

const fs = require('fs')
const input = fs.readFileSync('dev/stdin').toString().trim().split('\n')

let idx = 0

const counts = []
while (input[idx] !== '0 0') {
    const [width, height] = input[idx].split(' ').map(x => +x)
    const seaMap = []
    for (let i = 0; i < height; i++) {
        seaMap.push(input[++idx].split(' ').map(x => +x))
    }
    idx++

    let count = 0

    for (let h = 0; h < height; h++) {
        for (let w = 0; w < width; w++) {
            if (seaMap[h][w] === 1) {
                dfsIsland(h, w, height, width, seaMap)
                count++
            }
        }
    }

    counts.push(count)
}

console.log(counts.join('\n'))

길을 가다가 1을 만나면 0으로 바꾸고 미친듯이 사방으로 파고 들어가서 전부 0으로 바꿔놔야 직성이 풀리는 함수 dfsIsland.

왓챠피디아 클론코딩

https://github.com/fancyers/clone-watcha-backend
영화 목록 조회, 영화 세부정보 조회, 별점 기능 등 구현

profile
개발자

0개의 댓글