Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weโ€™ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

14-avocado 13 #67

Merged
merged 2 commits into from
Feb 20, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 37 additions & 0 deletions avocado-13/DFS&BFS/DFS์™€ BFS.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
from collections import deque
# bfs ๋ฉ”์„œ๋“œ ์ •์˜
def bfs(graph, start, visited):
queue = deque([start])
visited[start] = True
result = [start] # ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ ์ €์žฅํ•  ๋ฆฌ์ŠคํŠธ
while queue:
v = queue.popleft()
for i in sorted(graph[v]): # ์ž‘์€ ๋ฒˆํ˜ธ๋ถ€ํ„ฐ ๋ฐฉ๋ฌธํ•˜๊ธฐ ์œ„ํ•ด ์ •๋ ฌ
if not visited[i]:
queue.append(i)
visited[i] = True
result.append(i) # ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ ๋ฆฌ์ŠคํŠธ์— ์ €์žฅ
return result

# dfs ๋ฉ”์„œ๋“œ ์ •์˜
def dfs(graph,start,visited):
visited[start] = True
result = [start] # ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ๋ฅผ ์ €์žฅํ•  ๋ฆฌ์ŠคํŠธ
for i in sorted(graph[start]): # ์ž‘์€ ๋ฒˆํ˜ธ๋ถ€ํ„ฐ ๋ฐฉ๋ฌธํ•˜๊ธฐ ์œ„ํ•ด ์ •๋ ฌ
if not visited[i]:
result.extend(dfs(graph,i,visited)) # ์žฌ๊ท€ ํ˜ธ์ถœ ๊ฒฐ๊ณผ๋ฅผ ๋ฆฌ์ŠคํŠธ์— ์ถ”๊ฐ€
return result

# ์–‘๋ฐฉํ–ฅ ๋ฆฌ์ŠคํŠธ ๋งŒ๋“ค๊ธฐ
n,m,start = map(int,input().split())
graph = [[] for i in range(n+1)]
for _ in range(m):
a,b= map(int,input().split())
graph[a].append(b)
graph[b].append(a)

dfs_visited = [False] * (n+1)
bfs_visited = [False] * (n+1)

print(*dfs(graph, start, dfs_visited)) # ๋ฆฌ์ŠคํŠธ๋ฅผ ์–ธํŒจํ‚นํ•˜์—ฌ ์ถœ๋ ฅ
print(*bfs(graph, start, bfs_visited)) # ๋ฆฌ์ŠคํŠธ๋ฅผ ์–ธํŒจํ‚นํ•˜์—ฌ ์ถœ๋ ฅ