[Algorithm] 네트워크

yongkini ·2021년 10월 5일
0

Algorithm

목록 보기
40/55

프로그래머스 네트워크 문제

문제 해석

: 문제 자체는 어렵지 않다. 컴퓨터의 수 n과 컴퓨터간의 연결관계를 나타내주는 2차원 배열을 받아서(0이면 비연결, 1이면 연결), 전체 네트워킹이 몇개나 형성돼있는지를 구하는 것이다. 이 때, 네트워크 단위는 연결단위이다. 즉, 예시처럼 1,2가 연결돼있고, 3은 혼자 떨어져있는데, 이 경우에는 2개의 네트워크가 존재하는 것.

구현 코드


def solution(n, computers):
    graph = {}
    path = {}
    answer = 0
    
    for i in range(n):
        graph[i] = []
        for idx, el in enumerate(computers[i]):
            if el == 1 and i!=idx:
                graph[i].append(idx)

                    
    def dfs(node):
        for el in graph[node]:
            try:
                if path[el]:
                    continue
            except:
                path[el] = True
                dfs(el)

    
    for key in list(graph.keys()):
        try:
            if path[key]:
                continue
        except:
            answer += 1 
            dfs(key)
            
    return answer

profile
완벽함 보다는 최선의 결과를 위해 끊임없이 노력하는 개발자

0개의 댓글