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

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

 

๋ฌธ์ œ ํ’€์ด

 ์ฃผ์–ด์ง„ ์ž…๋ ฅ ๊ฐ’ N, M์— ๋”ฐ๋ผ ๊ฐ„์„  ์ •๋ณด๋ฅผ ํ† ๋Œ€๋กœ ๊ทธ๋ž˜ํ”„๋ฅผ ์ดˆ๊ธฐํ™” ํ•ด์ค€ ํ›„ ๊ฐ ๋…ธ๋“œ๋งˆ๋‹ค ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ๋“ค๋กœ ๊ฒฝ๋กœ๋ฅผ ํƒ์ƒ‰ํ•˜๋ฉด ๋œ๋‹ค. ์ด๋•Œ ๋ฐฑํŠธ๋ž™ํ‚น์ด ํ•„์š”ํ•˜๋ฏ€๋กœ `DFS`๋กœ ํƒ์ƒ‰์„ ์ง„ํ–‰ํ•˜์—ฌ ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ์˜ ๊ฐœ์ˆ˜๊ฐ€ ํฌ๋ฉด ๊ฐฑ์‹ ์‹œ์ผœ์ฃผ๋ฉด ๋ฌธ์ œ๋ฅผ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋‹ค.

 

์ฝ”๋“œ

from collections import defaultdict


T = int(input())


def dfs(cur_node, cnt):
    global answer

    if answer < cnt:
        answer = cnt

    for next_node in graph[cur_node]:
        if not visited[next_node]:
            visited[next_node] = True
            dfs(next_node, cnt + 1)
            visited[next_node] = False


for test_case in range(1, T + 1):
    answer = 0
    n, m = map(int, input().split())
    graph = defaultdict(list)
    visited = [False] * (n + 1)

    for _ in range(m):
        node, other_node = map(int, input().split())
        # ๊ทธ๋ž˜ํ”„๋Š” ์–‘๋ฐฉํ–ฅ ์„ฑ์ด๋ฏ€๋กœ 2๋ฐฉํ–ฅ ๋ชจ๋‘ ์ถ”๊ฐ€
        graph[node].append(other_node)
        graph[other_node].append(node)

    # ์‹œ์ž‘ ๋…ธ๋“œ๋ฅผ ๋‹ค๋ฅด๊ฒŒ ํ•˜์—ฌ DFS๋กœ ๋…ธ๋“œ๋“ค์„ ํƒ์ƒ‰ํ•จ
    for node in range(1, n + 1):
        visited[node] = True
        dfs(node, 1)
        visited[node] = False

    print('#' + str(test_case), answer)

 ๋ฐฑํŠธ๋ž™ํ‚น์—์„œ๋Š” ํ•ญ์ƒ ์ฃผ์˜ํ•˜์—ฌ, ํŠน์ • ๊ฐ€์ง€์—์„œ `visited`๋ฅผ `True`๋กœ ํ•˜์˜€๋‹ค๋ฉด ํ˜ธ์ถœ ์Šคํƒ์—์„œ ๋ณต๊ท€ ํ›„์— ๋‹ค์‹œ `False`๋กœ ๋งŒ๋“ค์–ด ๋ฐฑํŠธ๋ž™ํ‚น์ด ๊ฐ€๋Šฅํ•˜๋„๋ก ํ•˜์—ฌ์•ผ ํ•œ๋‹ค.

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€