๐Ÿ—๏ธ Algorithm/โฌ› ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค

โฌ› [Programmers] [BFS/DFS] [Python] Level3_๋„คํŠธ์›Œํฌ

Dbswnstjd 2023. 2. 11. 19:01

๋ฌธ์ œ

https://school.programmers.co.kr/learn/courses/30/lessons/43162

 

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

์ฝ”๋“œ ์ค‘์‹ฌ์˜ ๊ฐœ๋ฐœ์ž ์ฑ„์šฉ. ์Šคํƒ ๊ธฐ๋ฐ˜์˜ ํฌ์ง€์…˜ ๋งค์นญ. ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค์˜ ๊ฐœ๋ฐœ์ž ๋งž์ถคํ˜• ํ”„๋กœํ•„์„ ๋“ฑ๋กํ•˜๊ณ , ๋‚˜์™€ ๊ธฐ์ˆ  ๊ถํ•ฉ์ด ์ž˜ ๋งž๋Š” ๊ธฐ์—…๋“ค์„ ๋งค์นญ ๋ฐ›์œผ์„ธ์š”.

programmers.co.kr

ํ’€์ด

# ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค 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 ๊ฐœ๋…์„ ์•Œ๊ณ ์žˆ๋‹ค๋ฉด ์‰ฝ๊ฒŒ ํ•ด๊ฒฐ์ด ๊ฐ€๋Šฅ ํ•  ๊ฒƒ์ด๋‹ค.