Algorithm/ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค / Python] ๋„คํŠธ์›Œํฌ

meeeeejin 2021. 3. 31. 17:07

๋ฌธ์ œ ๋งํฌ: programmers.co.kr/learn/courses/30/lessons/43162

 

์ฝ”๋”ฉํ…Œ์ŠคํŠธ ์—ฐ์Šต - ๋„คํŠธ์›Œํฌ

๋„คํŠธ์›Œํฌ๋ž€ ์ปดํ“จํ„ฐ ์ƒํ˜ธ ๊ฐ„์— ์ •๋ณด๋ฅผ ๊ตํ™˜ํ•  ์ˆ˜ ์žˆ๋„๋ก ์—ฐ๊ฒฐ๋œ ํ˜•ํƒœ๋ฅผ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค. ์˜ˆ๋ฅผ ๋“ค์–ด, ์ปดํ“จํ„ฐ A์™€ ์ปดํ“จํ„ฐ B๊ฐ€ ์ง์ ‘์ ์œผ๋กœ ์—ฐ๊ฒฐ๋˜์–ด์žˆ๊ณ , ์ปดํ“จํ„ฐ B์™€ ์ปดํ“จํ„ฐ C๊ฐ€ ์ง์ ‘์ ์œผ๋กœ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ

programmers.co.kr

 

๋ฌธ์ œ ์„ค๋ช…

BFS๋ฅผ ์ด์šฉํ•ด ์—ฐ๊ฒฐ๋œ ๋ชจ๋“  ์ปดํ“จํ„ฐ๋ฅผ ํƒ์ƒ‰ํ•˜๋Š” ๋ฐฉ๋ฒ•์œผ๋กœ ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ–ˆ์Šต๋‹ˆ๋‹ค. 

  1. ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ปดํ“จํ„ฐ ์ค‘ ์ž‘์€ ๋ฒˆํ˜ธ๋ถ€ํ„ฐ BFS ์ˆ˜ํ–‰
  2. BFS๊ฐ€ ๋๋‚˜๋ฉด ๋„คํŠธ์›Œํฌ ๊ฐœ์ˆ˜ 1 ์ฆ๊ฐ€ (answer++)
  3. ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€ ์ปดํ“จํ„ฐ๊ฐ€ ์—†์„ ๋•Œ๊นŒ์ง€ 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