From bec3662128700314880a958035b419c5329d7b07 Mon Sep 17 00:00:00 2001 From: AEJIJEON Date: Mon, 24 May 2021 23:31:40 +0900 Subject: [PATCH] =?UTF-8?q?programmers=20level1=20=EB=84=A4=ED=8A=B8?= =?UTF-8?q?=EC=9B=8C=ED=81=AC=20solution?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ...44\355\212\270\354\233\214\355\201\254.py" | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 "AejiJeon/programmers/210516sprint/\353\204\244\355\212\270\354\233\214\355\201\254.py" diff --git "a/AejiJeon/programmers/210516sprint/\353\204\244\355\212\270\354\233\214\355\201\254.py" "b/AejiJeon/programmers/210516sprint/\353\204\244\355\212\270\354\233\214\355\201\254.py" new file mode 100644 index 0000000..a4fbc03 --- /dev/null +++ "b/AejiJeon/programmers/210516sprint/\353\204\244\355\212\270\354\233\214\355\201\254.py" @@ -0,0 +1,30 @@ +# graph is represented in adjacent matrix -> find the number of connected components +from collections import deque + +# explores all nodes of a connected component +def bfs(graph, visited, start, n): + q = deque() + q.append(start) + visited[start] = True + while q: + now = q.popleft() + for i in range(n): + if graph[now][i] == 1 and not visited[i]: + q.append(i) + visited[i] = True + + +def solution(n, computers): + answer = 0 + visited = [False] * n + for i in range(n): + # find connected component + if not visited[i]: + # explores all nodes of the component + bfs(computers, visited, i, n) + answer += 1 + return answer + + +print(solution(3, [[1, 1, 0], [1, 1, 0], [0, 0, 1]])) +print(solution(3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]])) \ No newline at end of file