
๋จ์ํ DFS์ BFS๋ฅผ ๊ตฌํํ์ฌ ์ถ๋ ฅํ๋ฉด ๋๋ค.
๊ทธ๋ํ ๊ตฌํ
graph = [[0]*(N+1) for x in range(N+1)]
for i in range(M):
temp = list(map(int, input().split(' ')))
graph[temp[0]][temp[1]] = 1
graph[temp[1]][temp[0]] = 1
๊ทธ๋ํ๋ 2์ฐจ์ ๋ฐฐ์ด๋ก ๊ตฌํํ์๋ค.
๋ ์ ์ ์ ์ฐ๊ฒฐํ๋ ๊ฐ์ ์ 1๋ก ๋ฐ๊ฟ์ค๋ค. ์๋ฐฉํฅ ๊ทธ๋ํ์ด๊ธฐ ๋๋ฌธ์ ๋ ๋ฒ ๋ฐ๊ฟ์ฃผ์ด์ผ ํ๋ค.
์๋ฅผ๋ค์ด ๊ฐ์ ์ด 1๊ณผ 2๋ฅผ ์ฐ๊ฒฐํ๋ค๋ฉด, 2์ฐจ์ ๋ฐฐ์ด์ ๋ค์๊ณผ ๊ฐ๋ค.

DFS ๊ตฌํ
ํ์์ ์์ํ ์ ์ ์ ํ๋ผ๋ฏธํฐ๋ก ๋ฐ์ dfs๋ฅผ ์ํํ๋ ํจ์์ด๋ฉฐ, recursive๋ก ๊ตฌํํ์๋ค.
graph์์ ์ฐ๊ฒฐ๋ ์ ์ ์ ๋ฆฌ์คํธ๋ก ๋ง๋ค๊ณ , ๋ฆฌ์คํธ์ ํด๋นํ๋ ์ ์ ์ค ๋ฐฉ๋ฌธํ์ง ์์ ์ ์ ์ผ๋ก dfs๋ฅผ ์ํํ๋ค.
def DFS(v , visit):
visit.append(v)
stack = [v]
while stack :
temp = stack.pop()
for i in list(filter(lambda x : graph[temp][x] == 1, range(len(graph[0])))) :
if i not in visit :
visit = DFS(i, visit)
return visit
BFS ๊ตฌํ
ํ์์ ์์ํ ์ ์ ์ ํ๋ผ๋ฏธํฐ๋ก ๋ฐ์ bfs๋ฅผ ์ํํ๋ ํจ์์ด๋ค.
DFS ํจ์์ ๊ตฌํ๋ฐฉ์์ ๋น์ทํ์ง๋ง recursive๋ฅผ ์ฌ์ฉํ์ง ์์๋ค.
def BFS(v):
queue = [v]
visit = [v]
while queue :
temp = queue.pop(0)
for i in list(filter(lambda x : graph[temp][x] == 1, range(len(graph[0])))) :
if i not in visit :
visit.append(i)
queue.append(i)
return visit
์ ์ฒด์ฝ๋
N, M, V = list(map(int, input().split(' ')))
graph = [[0]*(N+1) for x in range(N+1)]
for i in range(M):
temp = list(map(int, input().split(' ')))
graph[temp[0]][temp[1]] = 1
graph[temp[1]][temp[0]] = 1
def DFS(v , visit):
visit.append(v)
stack = [v]
while stack :
temp = stack.pop()
for i in list(filter(lambda x : graph[temp][x] == 1, range(len(graph[0])))) :
if i not in visit :
visit = DFS(i, visit)
return visit
def BFS(v):
queue = [v]
visit = [v]
while queue :
temp = queue.pop(0)
for i in list(filter(lambda x : graph[temp][x] == 1, range(len(graph[0])))) :
if i not in visit :
visit.append(i)
queue.append(i)
return visit
for i in DFS(V, []):
print(i, end = ' ')
print()
for i in BFS(V):
print(i, end = ' ')

ํ ๋ฒ ์ํ๋ ธ์ง,,
'๐ Algorithm > Python' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] ๋ฐฑ์ค 2089 (0) | 2021.03.04 |
---|---|
[Python] ๋ฐฑ์ค 1442 (0) | 2021.02.25 |
[Python] ๋ฐฑ์ค 6549 (0) | 2021.02.20 |
[Python] ๋ฐฑ์ค 2606 (0) | 2020.09.01 |
[Python] ๋ฐฑ์ค 2231 (0) | 2020.05.03 |