Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Algorithm] 네트워크 #163

Closed
hwangJi-dev opened this issue Mar 29, 2023 · 0 comments
Closed

[Algorithm] 네트워크 #163

hwangJi-dev opened this issue Mar 29, 2023 · 0 comments

Comments

@hwangJi-dev
Copy link
Owner

hwangJi-dev commented Mar 29, 2023

💬 문제

https://school.programmers.co.kr/learn/courses/30/lessons/43162


💬 Idea

네트워크를 표현하는 연결 리스트 그래프를 먼저 만든 후, 0부터 시작하여 연결된 모든 노드를 탐색한다.

  1. 이렇게 한 네트워크망이 생성되면 +1을 한다.
  2. 네트워크망 생성 후 아직 탐색되지 않은 노드가 남아있다면, 해당 노드를 start로 하여 또 다른 네트워크망이 있는지 탐색한다.
  3. 네트워크가 남아있지 않을때까지 1-2를 반복한다.

💬 풀이

func solution(n:Int, computers:[[Int]]) -> Int {
    var networkDict: [Int: [Int]] = [:]
    
    for (i, ci) in computers.enumerated() {
        if networkDict[i] == nil {
            networkDict[i] = []
        }
        
        for (j, _) in ci.enumerated() {
            if computers[i][j] == 1 {
                networkDict[i]?.append(j)
            }
        }
    }
    return dfsToFindNetwork(networkDict, 0)
}

func dfsToFindNetwork(_ arr: [Int: [Int]], _ start: Int) -> Int {
    var arr = arr
    var networkCount = 0
    var needVisitStack: [Int] = [start]
    var visitedQueue: [Int] = []
    
    while !needVisitStack.isEmpty {
        let node = needVisitStack.removeLast()
        if visitedQueue.contains(node) { continue }
        
        visitedQueue.append(node)
        needVisitStack += arr[node] ?? []
        
        if ((arr[node]?.isEmpty) != nil) {
            arr.removeValue(forKey: node)
        }
    }
    networkCount += 1
    
    if arr.count > 0 {
        networkCount += dfsToFindNetwork(arr, arr.first!.key)
    }
    
    return networkCount
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant