๋ฌธ์ ๋งํฌ: 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
'Algorithm > ํ๋ก๊ทธ๋๋จธ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[ํ๋ก๊ทธ๋๋จธ์ค / Python] ์ฌํ๊ฒฝ๋ก (0) | 2021.04.01 |
---|---|
[ํ๋ก๊ทธ๋๋จธ์ค / Python] ๋จ์ด ๋ณํ (0) | 2021.03.31 |
[ํ๋ก๊ทธ๋๋จธ์ค / Python] ํ๊ฒ ๋๋ฒ (0) | 2021.03.15 |
[ํ๋ก๊ทธ๋๋จธ์ค / C++] ์ง๊ฒ๋ค๋ฆฌ (0) | 2021.02.02 |
[ํ๋ก๊ทธ๋๋จธ์ค / C++] ๋จ์์นด๋ฉ๋ผ (0) | 2021.02.01 |