네트워크

Sett·2021년 9월 3일
0

문제

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

문제 접근

  1. 내가 못 풀었다.
  2. 연결 되어 있지 않으면 answer 카운트
  3. 재귀를 통해 2차원 배열의 한 요소(배열)에 들어가, 모든 경우를 다 탐색한 다음,
  4. 방문 정보를 visit에 기록한다.
  5. 연결 점이 없을 경우, main의 for문에 들어오게 되며, 그때마다 answer를 하나씩 + 한다. (네트워크가 분리 되어있어서 개별의 개수를 가진다, 라는 표기)

소스 코드

func solution(_ n:Int, _ computers:[[Int]]) -> Int {
    var answer = 0
    var copycomputers = computers
    var visited = Array<Bool>(repeating: false, count: n)
    
    for i in 0..<n {
        if !visited[i] {
            answer += 1
            dfs(point: i, visited: &visited, computers: &copycomputers, n: n)
        }
    }
    
    return answer
}
func dfs(point: Int, visited: inout [Bool], computers: inout [[Int]], n: Int) {
    visited[point] = true
    for i in 0..<n {
        if !visited[i] && computers[point][i] == 1 {
            dfs(point: i, visited: &visited, computers: &computers, n: n)
        }
    }
}
profile
안녕하세요

0개의 댓글

관련 채용 정보