[프로그래머스] 네트워크

awmaker·2021년 7월 25일

Algorithm

목록 보기
5/9
post-thumbnail

[프로그래머스] 네트워크

const dfs = (stack, computers, visited) => {
    // 스택이 없으면 종료
    if (!stack.length) return
    // 스택에서 뽑은 데이터에서 방문할 컴퓨터를 정의
    const nowVisit = stack.pop()

    // 방문한 컴퓨터의 네트워크 구성을 불러와서 targetComputer, isLinked에 각각 컴퓨터의 번호, 연결여부를 담아 반복
    for (let [targetComputer, isLinked] of computers[nowVisit].entries()) {
        // 타겟 컴퓨터와 연결되어있다면
        if (isLinked) {
            // 타겟 컴퓨터를 아직 방문하지 않았다면
            if (!visited[targetComputer]) {
                // 방문이력을 true로 바꾸고
                visited[targetComputer] = true
                // 스택에 타겟 컴퓨터 번호를 추가
                stack.push(targetComputer)
            }
        }
    }

    // 재귀
    dfs(stack, computers, visited)
}

const solution = (n, computers) => {
    const visited = new Array(computers.length).fill(false)
    let networkCount = 0

    while (visited.includes(false)) {
        const nowVisit = visited.findIndex((v) => v === false)
        if (nowVisit != undefined) {
            visited[nowVisit] = true
            dfs([nowVisit], computers, visited)
            networkCount++
        }
    }

    return networkCount
}
profile
From design to DevOps with frontend and backend.

0개의 댓글