[백준] 1260번 : DFS와 BFS - Python(파이썬)

강재원·2022년 11월 24일
0

[코딩테스트] Python

목록 보기
188/200
post-custom-banner



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

from collections import deque

def dfs(w):
    check[w]=True
    print(w,end=' ')
    for i in range(1,n+1):
        if edge[w][i]==1 and check[i]==False: dfs(i)

def bfs(s):
    q=deque()
    q.append(s)
    check1[s]=True

    while len(q)>0:
        s=q.popleft()
        print(s,end=' ')
        for i in range(1,n+1):
            if edge[s][i]==1 and check1[i]==False:
                q.append(i)
                check1[i]=True

n,m,v=map(int,input().split())
edge=[[0 for _ in range(n+1)] for _ in range(n+1)]
check=[False for _ in range(n+1)]
check1=[False for _ in range(n+1)]

for i in range(m):
    f,t=map(int,input().split())
    edge[f][t]=edge[t][f]=1

dfs(v)
print()
bfs(v)
profile
개념정리 & 문법 정리 & 알고리즘 공부
post-custom-banner

0개의 댓글