본문 바로가기

알고리즘 문제풀이/[Python] 백준

[백준 1260번 / 실버2] DFS와 BFS - (Graph Traversal)

문제링크 :  https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

첫째 줄에 정점의 개수 N(1 ≤ N ≤ 1,000), 간선의 개수 M(1 ≤ M ≤ 10,000), 탐색을 시작할 정점의 번호 V가 주어진다. 다음 M개의 줄에는 간선이 연결하는 두 정점의 번호가 주어진다. 어떤 두 정점 사

www.acmicpc.net

 

DFS와 BFS 코드에서 굳이 visited라는 리스트를 return해 주지 않고도 코드를 작성할 수 있다.

사실 visited를 return하는 방법과 하지않는 방법 중에서 어떤것이 더 좋은 코드인지 잘 모르겠다..ㅎ

 

 

from collections import deque

def DFS(graph,v,visited=None):
  visited.append(v)
  for w in graph[v]:
    if w not in visited:
      DFS(graph,w,visited)
  return visited

def BFS(graph,v):
  queue=deque([v])
  visited=[v]
  while queue:
    v=queue.popleft()
    for w in graph[v]:
      if w not in visited:
        queue.append(w)
        visited.append(w)
  return visited


vertex,edge,start=map(int,input().split())
graph={i:[] for i in range(vertex+1)}
for i in range(edge):
  v,w=map(int,input().split())
  graph[v].append(w)
  graph[w].append(v)

for i in range(vertex+1):
  graph[i].sort()

visited=[]
result1=DFS(graph,start,visited)
result2=BFS(graph,start)

print(" ".join(list(map(str,result1))))
print(" ".join(list(map(str,result2))))