ํ”„๋กœ๊ทธ๋ž˜๋จธ์Šค [lv3] ๋„คํŠธ์›Œํฌ ํŒŒ์ด์ฌ

2021. 4. 25. 14:59ใ†๐Ÿ”ฑ Algorithm/Else

 

 

์ ‘๊ทผ

1. ์ฃผ์–ด์ง„ ๊ฒƒ์„ ์ •๋ฆฌ : ๋…ธ๋“œ(์ปดํ“จํ„ฐ)์˜ ๊ฐฏ์ˆ˜, ๋น„๋ฐฉํ–ฅ์„ฑ, ์—ฐ๊ฒฐ์„ 


2. ์ฒซ ์‹œ๋„: key(์ปดํ“จํ„ฐ) - value (key์™€ ์—ฐ๊ฒฐ๋œ ์ปดํ“จํ„ฐ) ๊ตฌ์กฐ์˜ dictionary ์ž‘์„ฑ ์‹œ๋„ -> ๋ชปํ’ˆ ใ…Ž ใ… 

3. dfs๋กœ ์ ‘๊ทผ : ์ด๋ฏธ ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ ์ฒดํฌํ•˜๊ธฐ ์œ„ํ•ด visited ๋ฆฌ์ŠคํŠธ ์ƒ์„ฑ
-> ์›์†Œ๋Š” ๋ชจ๋‘ 0์œผ๋กœ ์ฑ„์šฐ๊ณ , while๋ฌธ์œผ๋กœ 0์ด ๋‚˜์˜ค์ง€ ์•Š์„ ๋•Œ ๊นŒ์ง€ ์ฒดํฌ

4. ํ˜„์žฌ ๋ฐฉ๋ฌธ์ค‘์ธ ๋…ธ๋“œ(์ปดํ“จํ„ฐ)์™€ ์—ฐ๊ฒฐ๋œ ์ปดํ“จํ„ฐ๋ฅผ **๋ชจ๋‘** ์ฐพ๊ธฐ ์œ„ํ•ด dfs ์Šคํƒ ์„ ์–ธ

5. dfs ์Šคํƒ์— append๋  ์กฐ๊ฑด์€, ์•„์ง ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š์€(visited[i]==0) ๋™์‹œ์—(and) ํ˜„์žฌ ๋ฐฉ๋ฌธ์ค‘์ธ ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ ๋ผ(computers[curr][i]) ์žˆ์„ ๋•Œ

 

 

 

ํ’€์ด 1) ๋ฐ˜๋ณต๋ฌธ ์‚ฌ์šฉ 

def solution(n, computers):
    visited = [0] * n
    result = 0
    dfs = list()

    while 0 in visited:
        dfs.append(visited.index(0))
        while dfs:
            curr = dfs.pop()
            visited[curr] = 1
            for i in range(n):
                if computers[curr][i] == 1 and visited[i] == 0:
                    dfs.append(i)
        result += 1

    return result

 

 

ํ’€์ด 2) ์žฌ๊ท€๋ฌธ ์‚ฌ์šฉ

def solution(n, computers):
    answer = 0
    visited = [0] * n
    def dfs(computers, visited, start):
        stack = [start]
        while stack:
            j = stack.pop()
            visited[j] = 1
            for i in range(0, len(computers)):
                if computers[j][i] ==1 and visited[i] == 0:
                    stack.append(i)
	return
    
    i=0
    while 0 in visited:
        if visited[i] ==0:
            dfs(computers, visited, i)
            answer +=1
        i+=1
    return answer

 

 

์•„์‰ฌ์šด ์  ๋ฐ ์ •๋ฆฌ

1. ํ’€์ด 1๋ฒˆ : ์ด์ค‘ while ๋ฌธ ๊ตฌ์„ฑ -> ์‹œ๊ฐ„๋ณต์žก๋„ O(n^2)
2. ์‹คํ–‰ ์†๋„๋Š” ํ’€์ด 1๋ฒˆ์ด ์กฐ๊ธˆ ๋” ๋น ๋ฅด๋‹ค. (๋ฐ˜๋ณต๋ฌธ์ด ์žฌ๊ท€๋ณด๋‹ค ๋น ๋ฅด๋‹ค)