ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90

๐Ÿšฉ ๊ทธ๋ž˜ํ”„์ด๋ก , ๊ทธ๋ž˜ํ”„ํƒ์ƒ‰, DFS, BFS

 

thinking

์ฒ˜์Œ์— ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋กœ ํ’€์—ˆ๋Š”๋ฐ ์ธํ’‹๊ฐ’์„ ๋ญ˜ ๋จผ์ € ๋ฐ›๋Š๋ƒ์— ๋”ฐ๋ผ dfs์—์„œ ์ˆœ์„œ๊ฐ€ ๋‹ฌ๋ผ์ ธ์„œ ์ธ์ ‘ํ–‰๋ ฌ๋กœ ํ’€์—ˆ๋‹ค.

(๊ฐ™์€ ๊ฑฐ๋ฆฌ์˜ ๋…ธ๋“œ๋ผ๋ฉด ์ˆซ์ž๊ฐ€ ์ž‘์€ ์ˆœ์œผ๋กœ ์ง„ํ–‰๋˜์•ผ ํ•˜๊ธฐ ๋•Œ๋ฌธ)

dfs๋Š” ์žฌ๊ท€์—ฌ์„œ ๊ทธ๋ƒฅ ๋ฐ”๋กœ๋ฐ”๋กœ ์ถœ๋ ฅํ•˜๊ณ ์ž ํ•จ์ˆ˜ ๋‚ด์— print์ฒ˜๋ฆฌํ–ˆ๊ณ , bfs๋Š” queue๋ฅผ ์ด์šฉํ•ด์„œ ํ’€์—ˆ๋‹ค.

 

์ฝ”๋“œ

def DFS(V):
    visited[V] = 1  # ๋ฐฉ๋ฌธ์ฒดํฌ
    print(V, end=' ')  # ์žฌ๊ท€์—ฌ์„œ ๋ฐ”๋กœ ์ถœ๋ ฅ
    for v in range(1, N+1):
        if not visited[v] and edge_matrix[V][v] == 1:
            DFS(v)


def BFS(V):
    queue = [V]  # ์ถœ๋ฐœ์ 
    visited = [V]  # ๋ฐฉ๋ฌธ
    while queue:
        t = queue.pop(0)
        for v in range(1, N+1):
            if v not in visited and edge_matrix[t][v] == 1:
                queue.append(v)
                visited.append(v)
    return visited


T = int(input())
for tc in range(1, T+1):
    N, M, V = map(int, input().split())  # N:์ •์ ๊ฐœ์ˆ˜, M:๊ฐ„์„ ๊ฐœ์ˆ˜, V:์‹œ์ž‘์ •์  ๋ฒˆํ˜ธ
    edge_matrix = [[0]*(N+1) for _ in range(N+1)]
    for _ in range(M):
        s, e = map(int, input().split())
        edge_matrix[s][e] = 1
        edge_matrix[e][s] = 1

    visited = [0] * (N+1)  # dfs ๋ฐฉ๋ฌธ์ฒดํฌ์šฉ

    DFS(V)
    print()
    print(*BFS(V))

 

๋Œ“๊ธ€