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๋ฒ์ด ์กฐ๊ธ ๋ ๋น ๋ฅด๋ค. (๋ฐ๋ณต๋ฌธ์ด ์ฌ๊ท๋ณด๋ค ๋น ๋ฅด๋ค)
'๐ฑ Algorithm > Else' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
ํ๋ก๊ทธ๋๋จธ์ค [lv2] ๊ฐ์ฅ ํฐ ์ ์ฌ๊ฐํ ํ์ด์ฌ (0) | 2021.05.15 |
---|---|
ํ๋ก๊ทธ๋๋จธ์ค [lv2] ๊ดํธ๋ณํ ํ์ด์ฌ (0) | 2021.04.25 |
ํ๋ก๊ทธ๋๋จธ์ค [lv2] ์คํ์ฑํ ๋ฐฉ ํ์ด์ฌ (0) | 2021.04.25 |
ํ๋ก๊ทธ๋๋จธ์ค [lv3] ๋จ์ด๋ณํ ํ์ด์ฌ (0) | 2021.04.25 |
ํ๋ก๊ทธ๋๋จธ์ค [lv2] ํ๊ฒ๋๋ฒ ํ์ด์ฌ (0) | 2021.04.05 |