Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
Archives
Today
Total
관리 메뉴

NISSO

[백준 1260] DFS와 BFS 본문

Coding Test

[백준 1260] DFS와 BFS

oniss 2021. 7. 2. 13:17
def dfs(v):
    print(v, end=' ')
    visit[v] = 1
    for i in range(1,n+1):
        if s[v][i]==1 and visit[i]==0:
            dfs(i)

def bfs(v):
    queue = [v]
    visit[v] = 0
    while queue:
        v = queue[0]
        print(v, end=' ')
        queue.pop(0)
        for i in range(1,n+1):
            if s[v][i]==1 and visit[i]==1:
                queue.append(i)
                visit[i] = 0


n,m,v = map(int, input().split())
s = [[0]*(n+1) for _ in range(n+1)]
visit = [0]*(n+1)
for _ in range(m):
    x,y = map(int, input().split())
    s[x][y] = 1
    s[y][x] = 1

dfs(v)
print()
bfs(v)

 

DFS와 BFS 구현의 기본 중 기본. 물론 코드는 내 코드가 아니다 : https://pacific-ocean.tistory.com/260

 

제일 깔끔한 것 같아서 이 코드를 보고 이해하고, 혼자 작성할 수 있을 때까지 2~3번 반복했다.

더 확실히 공부하고 다른 응용 문제들도 풀고 싶지만, 이제 2차 코테가 6시간도 남지 않았으니 프로그래머스 고득점 키트 몇 개를 풀어봐야겠다.

Comments