[백준]dfs와 bfs

백준 온라인 저지

DFS와 BFS

링크 : 문제 바로가기

import sys
n,m,v=map(int,sys.stdin.readline().rstrip().split(" "))
linked=[[] for _ in range(n+1)]
visited=[False]*(n+1)
result=[]
for _ in range(m):
    x,y=map(int,sys.stdin.readline().rstrip().split(" "))
    linked[x].append(y)
    linked[y].append(x)
# print(linked)

# 스택에 맨 처음 수 하나 넣음

# 스택에서 맨 위부터 하나씩 빼서 검사함
# 검사중인 요소는 연결된 수들이 있는지 없는지 체크한다.
# 있으면
# 검사중인 요소와 연결된 수들을 가장 큰수부터 스택에 담는다.
# 없으면
# pass

# 스택이 빌때까지 위내용 계속 반복

stack=[v]

while len(stack)!=0:
    checking=stack.pop()
    if visited[checking]==True:
        continue
    visited[checking]=True
    result.append(checking)

    if len(linked[checking])!=0:
        stackinput=sorted(linked[checking])
        while len(stackinput)!=0:
            stack.append(stackinput.pop())
    else:
        pass

# print(result)
while len(result)!=0:
    print(result.pop(0))


# 큐에 맨 처음 수 하나 넣음

# 큐에서 맨 아래부터 하나씩 빼서 검사함
# 검사중인 요소는 연결된 수들이 있는지 없는지 체크한다.
# 있으면
# 검사중인 요소와 연결된 수들을 가장 작은수부터 큐에 담는다.
# 없으면
# pass

# 큐가 빌때까지 위내용 계속 반복
visited=[False]*(n+1)
result=[]

queue=[v]

while len(queue)!=0:
    checking=queue.pop(0)
    if visited[checking]==True:
        continue
    visited[checking]=True
    result.append(checking)

    if len(linked[checking])!=0:
        queueinput=sorted(linked[checking])
        while len(queueinput)!=0:
            queue.append(queueinput.pop(0))
    else:
        pass

# print(result)
while len(result)!=0:
    print(result.pop(0))
  • DFS : 스택 이용, 인접리스트 이용, 탐색여부를 알기위해 visited리스트 생성
  • BFS : 큐 이용, 인접리스트 이용, 탐색여부를 알기위해 visited리스트 생성

알고리즘 : 그래프 이론, 그래프 탐색, 너비 우선 탐색, 깊이 우선 탐색

results matching ""

    No results matching ""