๋ฌธ์
https://school.programmers.co.kr/learn/courses/30/lessons/43162
ํ์ด
# ํ๋ก๊ทธ๋๋จธ์ค 3๋จ๊ณ - ๋คํธ์ํฌ
from collections import deque
def bfs(graph, visited, n):
if visited[n] == 1:
return 0
q = deque()
q.append((n))
visited[n] = 1
while q:
v = q.popleft()
for i in graph[v]:
if not visited[i]:
visited[i] = 1
q.append((i))
return 1
def solution(n, computers):
answer = 0
graph = [[] for _ in range(n)]
visited = [0 for _ in range(n)]
for i in range(len(computers)):
for j in range(len(computers[i])):
if i == j:
continue
if computers[i][j] == 1:
graph[i].append(j)
for i in range(len(graph)):
answer += bfs(graph, visited, i)
return answer
print(solution(3, [[1, 1, 0], [1, 1, 1], [0, 1, 1]]))
BFS๋ฅผ ์ฌ์ฉํ์ฌ ํ์๋ค. ์ปดํจํฐ ๋ ธ๋๋ฅผ ํตํด ๊ทธ๋ํ๋ฅผ ์์ฑํ ํ BFS๋ฅผ ํตํด ๋คํธ์ํฌ ๊ฐ์๋ฅผ ์ธ์ด์ค๋ค.
์ค์ํ๋ ๊ฒ์ ๋คํธ์ํฌ์ ๊ฐ์๋ฅผ ์ ๋ ํผ์๋ง ์ฐ๊ฒฐ๋์ด ์์ผ๋ฉด ์์ธ์ฒ๋ฆฌ๋ฅผ ํด์ฃผ์ง ์์์ ์กฐ๊ธ ํค๋ฉ์๋ค.
๋ค๋ฅธ ๋ถ๋ถ๋ค์ BFS ๊ฐ๋ ์ ์๊ณ ์๋ค๋ฉด ์ฝ๊ฒ ํด๊ฒฐ์ด ๊ฐ๋ฅ ํ ๊ฒ์ด๋ค.