728x90
๋ฐ์ํ
# ์ ์ ๊ฐ์ N, ๊ฐ์ ๊ฐ์ M, ํ์ ์์ ๋ฒํธ V
N, M, V = map(int, input().split())
edgeList = []
graph = [[] for vertex in range(N+1)]
for i in range(M):
e0, e1 = map(int, input().split())
edgeList.append((e0, e1))
for edge in edgeList:
graph[edge[0]].append(edge[1])
graph[edge[1]].append(edge[0])
for i in range(len(graph)):
graph[i].sort(reverse=True)
#DFS
def DFS(graph, V) :
visited = []
stack = [V]
while stack :
print("-------------------")
current = stack.pop()
if current in visited: # ์ด๋ฏธ ๋ฐฉ๋ฌธํ ๋
ธ๋๋ ๋ฌด์
continue
print("ํ์ฌ ๋ฐฉ๋ฌธ", current)
for n in graph[current]:
print("์ด์",n)
if not n in visited:
print("๋ฐฉ๋ฌธํด์ผํ ์ด์",n)
stack.append(n)
print("์คํ", stack)
visited.append(current) # ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
print("๋ฐฉ๋ฌธ์ฒ๋ฆฌ", visited)
return visited
print(DFS(graph, V))
#BFS
728x90
๋ฐ์ํ
'๐ป ์ฝ๋ฉํ ์คํธ > ์๊ณ ๋ฆฌ์ฆ' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๊น์ด์ฐ์ ํ์(DFS), ๋๋น์ฐ์ ํ์ (BFS) - python์ผ๋ก ๊ตฌํํ๊ธฐ (1) | 2025.03.27 |
---|