DFS와 BFS (백준 1260)

이재하·2023년 2월 2일
0

from collections import deque

def bfs(v): #breadth first search 너비 우선 탐색)
    q = deque([v])
    visited2[v] = True #방문 기록 저장
    while q:
        v = q.popleft()
        print(v,end=" ")
        for i in range(1,n+1): #v와 연결이 되어있는 것을 찾는다, 다 찾으면 다음 v, 먼저 들어온 순서로 빠진다
            if visited2[i] == 0 and graph[v][i] ==1:
                q.append(i)
                visited2[i] = True
def dfs(v):
    visited1[v] = True 
    print(v,end=' ')
    for i in range(1,n+1):
        if visited1[i] ==0 and graph[v][i] ==1:
            dfs(i) #연결 되어있으면 재귀함수로 바로 다음 i와 연결된 것 검사


n,m,v = map(int,input().split())

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

for _ in range(m):
    a,b = map(int,input().split())
    graph[a][b] = True
    graph[b][a] = True
visited1 = [False] * (n+1)
visited2 = [False] * (n+1)

dfs(v)
print()
bfs(v)

0개의 댓글