220. DFS와 BFS

아현·2021년 7월 19일
0

Algorithm

목록 보기
229/400
post-custom-banner

백준




1. Python



import sys
from collections import deque
input = sys.stdin.readline
n, m, start = map(int, input().split())

graph = [[0] * (n + 1) for _ in range(n + 1)]

for _ in range(m):
  a, b = map(int, input().split())
  graph[a][b] = graph[b][a] = 1
  

def dfs(start, visit = []):
  visit.append(start)
  print(start, end=' ')
  for i in range(len(graph[start])):
    if graph[start][i] == 1 and i not in visit:
      dfs(i, visit)

def bfs(start):
  visit = [start]
  queue = deque() 
  queue.append(start)

  while queue:
    now = queue.popleft()
    print(now, end=' ')
    for i in range(len(graph[now])):
      if graph[now][i] == 1 and (i not in visit):
        visit.append(i)
        queue.append(i)

dfs(start)
print()
bfs(start)


profile
For the sake of someone who studies computer science
post-custom-banner

0개의 댓글