๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/programmers

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค Level 3 - ๋„คํŠธ์›Œํฌ

by HandHand 2021. 3. 1.

๋ฌธ์ œ

ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค - ๋„คํŠธ์›Œํฌ

ํ’€์ด ๊ณผ์ •

์ฃผ์–ด์ง„ ์ธ์ ‘ํ–‰๋ ฌ์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๊ทธ๋ž˜ํ”„ ๋‚ด์˜ ์ปดํฌ๋„ŒํŠธ ๊ฐœ์ˆ˜๋ฅผ ์„ธ๋Š” ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๊ฐ ์ •์ ๋ณ„๋กœ DFS ํƒ์ƒ‰์„ ํ†ตํ•ด ๋ฐฉ๋ฌธ ๊ฐ€๋Šฅํ•œ ๋ชจ๋“  ์ •์ ์„ ๋ฐฉ๋ฌธํ•ด์ฃผ๋ฉด ํ•ด๋‹น ์ •์ ์ด ์†ํ•œ ์ปดํฌ๋„ŒํŠธ๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

๋”ฐ๋ผ์„œ ์ด DFS ํƒ์ƒ‰์ด ๋ช‡๋ฒˆ ์ˆ˜ํ–‰๋˜์—ˆ๋Š”์ง€ ํŒŒ์•…ํ•œ๋‹ค๋ฉด ๋„คํŠธ์›Œํฌ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

์ฝ”๋“œ


def dfs(n, adj, visit, here):
    visit[here] = 1

    for there in range(n):
        if adj[here][there] and not visit[there]:
            dfs(n, adj, visit, there)


def solution(n, computers):
    visit = [0 for _ in range(n)]

    network = 0
    for v in range(n):
        if not visit[v]:
            dfs(n, computers, visit, v)
            network += 1

    return network
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€