1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | from collections import deque def bfs(start, computers, visited): q = deque([start]) while q: v = q.popleft() visited[v] = True for idx, val in enumerate(computers[v]): if idx == v: continue if val == 1 and not visited[idx]: q.append(idx) def solution(n, computers): answer = 0 visited = [False] * n for i in range(n): if not visited[i]: answer += 1 bfs(i, computers, visited) return answer | cs |