ylab 2023. 3. 7. 14:57

https://www.acmicpc.net/problem/1260

 

1260번: DFS와 BFS

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

www.acmicpc.net

import sys
from collections import deque
input = sys.stdin.readline
n,m,v = list(map(int,input().split()))
adj = [[] for _ in range(n+1)]

for _ in range(m):
    x,y = list(map(int,input().split()))
    adj[x].append(y)
    adj[y].append(x)
#작은 값부터 먼저 방문하기 위한 정렬    
for i in range(1,n+1):
    adj[i].sort()
    

#print(adj)
#print(visit)
#이거 dfs함수 안에 넣으면 재귀이기 때문에 무한으로 빠짐
visit = [0] * (n+1)
def dfs(x):
    
    visit[x] =1
    print(x,end=' ')
    for y in adj[x]:
        #만약 방문한거면 dfs하지 않고 다음으로 넘어가
        if visit[y]:
            continue
        dfs(y)
        
def bfs(x):
    visit = [0] * (n+1)
    q = deque()
    q.append(x)
    visit[x]=1
    while q:
        x=q.popleft()
        print(x,end=' ')
        for y in adj[x]:
            if visit[y]:
                continue
            visit[y]=1
            q.append(y)
dfs(v)
print()
bfs(v)

 

항상 기초가 중요띠..

옛날에 풀었는데 또 새록새록하다..

틀에 연연하지 말고 유연하게 생각할 수 있도록하자

 

그리고 continue는 현재 반복되는거 종료 후 다음 반복문 실행

break는 가장 가까운 반복문 완전 종료