Algorithm/ํ๋ก๊ทธ๋๋จธ์ค
[ํ๋ก๊ทธ๋๋จธ์ค / Python] ๋คํธ์ํฌ
meeeeejin
2021. 3. 31. 17:07
๋ฌธ์ ๋งํฌ: programmers.co.kr/learn/courses/30/lessons/43162
๋ฌธ์ ์ค๋ช
BFS๋ฅผ ์ด์ฉํด ์ฐ๊ฒฐ๋ ๋ชจ๋ ์ปดํจํฐ๋ฅผ ํ์ํ๋ ๋ฐฉ๋ฒ์ผ๋ก ๋ฌธ์ ๋ฅผ ํด๊ฒฐํ์ต๋๋ค.
- ๋ฐฉ๋ฌธํ์ง ์์ ์ปดํจํฐ ์ค ์์ ๋ฒํธ๋ถํฐ BFS ์ํ
- BFS๊ฐ ๋๋๋ฉด ๋คํธ์ํฌ ๊ฐ์ 1 ์ฆ๊ฐ (answer++)
- ๋ฐฉ๋ฌธํ์ง ์์ ์ปดํจํฐ๊ฐ ์์ ๋๊น์ง 1~2๋ฒ์ ๋ฐ๋ณต ์ํ
์์ค์ฝ๋
from collections import deque
def solution(n, computers):
answer = 0
visited = [False] * n
def bfs(start, visited, computers):
visited[start] = True
queue = deque([start])
while queue:
v = queue.popleft()
for i in range(n):
# ๋ฐฉ๋ฌธํ์ง ์์ ์ฐ๊ฒฐ๋ ์ปดํจํฐ
if computers[v][i] == 1 and not visited[i]:
visited[i] = True
queue.append(i)
# ๋ฐฉ๋ฌธํ์ง ์์ ์ปดํจํฐ ์ค ์์ ๋ฒํธ๋ถํฐ BFS ์ํ
for i in range(n):
if not visited[i]:
bfs(i, visited, computers)
answer += 1
return answer
728x90