문제📖
풀이🙏
- 입력받은 노드간의 관계를 graph에 추가한다.
- dfs는 재귀적 호출을 통해 구현하고 bfs는 queue를 이용하여 구현한다.
코드💻
from collections import deque
v, e, start = map(int, input().split())
graph = [[] for _ in range(v+1)]
visited = [False] * (v+1)
for i in range(e):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
graph[a].sort()
graph[b].sort()
def bfs(graph, start, visited):
queue = deque([start])
visited[start] = True
while queue:
pop = queue.popleft()
print(pop, end = ' ')
for i in graph[pop]:
if not visited[i]:
queue.append(i)
visited[i] = True
def dfs(graph, v, visited):
visited[v] = True
print(v, end= ' ')
for i in graph[v]:
if not visited[i]:
dfs(graph, i, visited)
dfs(graph, start, visited)
print()
visited = [False] * (v+1)
bfs(graph, start, visited)