[프로그래머스 | BFS/DFS] 네트워크, Python

🏆 BFS

def solution(n, computers):
    answer = 0
    
    from collections import deque
    network = deque()
    
    for i in range(n):
        if computers[i][i] == 1:
            network.append(i)
            while network:
                root = network.popleft()                # BFS on root
                computers[root][root] = 0           # Myself - mark as 0, do not seek this node any more
                for idx, connected in enumerate(computers[root]):
                    if connected==1:
                        network.append(idx)               # Append connected computer on deque
                        computers[root][idx] = 0        # Mark as 0 (Visited), do not seek this node any more
                        computers[idx][root] = 0        # Mark as 0 (Visited), do not seek this node any more
            answer += 1
            
    return answer

전형적인 DFS/BFS 문제
방문한 노드는 0으로 표기해서 더이상 고려하지 않는게 포인트
BFS 중 더이상 방문할 노드가 없다면 (연결된 컴퓨터가 더이상 없다면), 새로운 root를 찾아 큐에 넣고 BFS 반복

좋은 웹페이지 즐겨찾기