Potato
์•ˆ๋…•ํ•˜์„ธ์š”, ๊ฐ์žก๋‹ˆ๋‹ค?๐Ÿฅ” ^___^ ๐Ÿ˜บ github ๋ฐ”๋กœ๊ฐ€๊ธฐ ๐Ÿ‘‰๐Ÿป

Algorithm/Programmers

[ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค] (Python) ๋„คํŠธ์›Œํฌ (lv.3) (DFS, ์žฌ๊ท€)

๊ฐ์ž ๐Ÿฅ” 2023. 2. 24. 15:37
๋ฐ˜์‘ํ˜•

ํŒŒ์ด์ฌ... ์ž…๋‹ˆ๋‹ค... ์ธ๋„ค์ผ์€ ๊ฑฐ์ง“๋ง์ด์—์š” ใ… ใ…  ์Šค์œ„ํ”„ํŠธ ์•„๋‹™๋‹ˆ๋‹ค.
SKํ”Œ๋ž˜๋‹› ์‹œํ—˜๋ณด๊ธฐ ์ง์ „.. ์•ฝ 6์‹œ๊ฐ„์ „์— Swift์–ธ์–ด ์‘์‹œ๊ฐ€ ๋ถˆ๊ฐ€ํ•˜๋‹ค๋Š” ํ†ต๋ณด๋ฅผ ๋ฐ›์•˜์Šด๋‹ค. ํ•˜ํ•˜ java / js / python๋งŒ ๋ณด๋”๊ตฐ์š”.. ์ด๋ฒˆ ์ฑ„์šฉ์—์„œ๋Š” ์ € ์„ธ ์–ธ์–ด๋ฅผ ๋‹ค๋ฃจ๋Š” ์ง๋ฌด์— TO๊ฐ€ ๋‚ซ๋‚˜๋ด์š”...? ๋„ค์ดํ‹ฐ๋ธŒ๋ฅผ ์•ˆ์“ฐ๋Š”๊ฑด๊ฐ€...
๊ทธ๋ž˜์„œ ๋ถ€๋žด๋ถ€๋žด ํŒŒ์ด์ฌ์œผ๋กœ ๊ฐ„๋‹จํ•˜๊ฒŒ๋‚˜๋งˆ ์‹œํ—˜์ค€๋น„๊ฒธ ๋ฌธ์ œ๋ฅผ ํ’€์–ด๋ดค์Šด๋‹ค. ํ•˜ํ•˜ ์–‘ํ•ด ๋ถ€ํƒ‚์“ฐ

โšซ๏ธ ๋ฌธ์ œ

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

 

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

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

programmers.co.kr

 

โšซ๏ธ ๋‚˜์˜ ํ’€์ด

๋ฌธ์ œ๋ฅผ ๋ณด์ž๋งˆ์ž DFS์ž„์„ ํŒŒ์•…ํ–ˆ๋‹ค. ํ•˜๋‚˜์˜ ๋…ธ๋“œ๋กœ ๋“ค์–ด๊ฐ€์„œ, ๊ฐ€์žฅ ๊นŠ์€๊ณณ๊นŒ์ง€ํƒ์ƒ‰ํ•˜๊ณ  ๊ทธ ์—ฐ๊ฒฐ๋œ ๊ฒƒ๋“ค์˜ count๋ฅผ ์„ธ์–ด์ฃผ๋ฉด ๋œ๋‹ค๊ณ  ํŒŒ์•…ํ–ˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค! DFS๋ฌธ์ œ์˜ ์ •์„์ด๋ผ๊ณ  ๋Š๊ปด์กŒ๋‹ค. ์‰ฌ์šฐ๋‹ˆ๊นŒ ๋ฐ”๋กœ ๊ตฌํ˜„ํ•ด๋ฒ„๋ฆฌ๊ธฐ

๊ทผ๋ฐ,,, dfs ๋Œ๋ฆด๋•Œ ์ƒˆ๋กœ ๊ฐฑ์‹ ๋˜๋Š” computerNum์„ ๋„˜๊ฒจ์ฃผ์–ด์•ผํ•˜๋Š”๋ฐ ์ดˆ๊ธฐ๊ฐ’์„ ๊ณ„์† ๋„˜๊ฒจ์ค˜์„œ ์žฌ๊ท€ ์ œํ•œ์— ๊ฑธ๋ ค์„œ ์งœ์ฆ๋‚˜์„œ ๋ฏธ์ณ๋ฒ„๋ฆฌ๋Š•๋ฃจ ์•Œ์•˜๋‹ค ใ…‹ใ…‹ใ…‹ใ…‹ใ…‹ ๊ฒฐ๊ตญ ์ปดํ“จํ„ฐ๋Š” ์ž˜๋ชป์ด์—†๊ณ  ๋‚ด๋ฌธ์ œ์—ฟ๋‹ค^^^ ํŒŒ์ด์ฌ ์š•ํ• ๋ป”...

โšซ๏ธ ์ •๋‹ต์ฝ”๋“œ

def solution(n, computers):

    visited = [False] * (n)
    answer = 0

    # dfs ํ•จ์ˆ˜
    def dfs(computerNumber):
        visited[computerNumber] = True

        for i in range(n):
            if i != computerNumber and computers[computerNumber][i] == 1:
                if visited[i] == False:
                    dfs(i)

    # ์ปดํ“จํ„ฐ ํ•˜๋‚˜์”ฉ start ์ง€์ ์œผ๋กœ ๋‹ค ๋ฐฉ๋ฌธํ•ด์•ผํ•จ
    for computerNumber in range(n):
        if visited[computerNumber] == False:
            dfs(computerNumber)
            answer += 1
    return answer

 

๋ฐ˜์‘ํ˜•