Post

[SWEA] 2814. ์ตœ์žฅ ๊ฒฝ๋กœ(python)

๐Ÿ“Œ๋ฌธ์ œ

Alt text

๐Ÿ’ช์•„์ด๋””์–ด

  1. ๊ทธ๋ž˜ํ”„ ๊ฐ„์„ ํ‘œ์‹œ
    2์ฐจ์›๋ฐฐ์—ด๋กœ ํ‘œ์‹œํ•  ์ˆ˜ ๋„ ์žˆ์ง€๋งŒ defaultdict์ด ๋” ํŽธํ•ด์„œ ๋”•์…”๋„ˆ๋ฆฌ๋ฅผ ์‚ฌ์šฉํ•˜์˜€๋‹ค. key๋Š” ๋…ธ๋“œ๋ฒˆํ˜ธ, value๋Š” ์—ฐ๊ฒฐ๋œ ๋…ธ๋“œ์˜ ๋ฒˆํ˜ธ
  2. ๋…ธ๋“œ ๋ฐฉ๋ฌธ
    dfs๋ฅผ ์‚ฌ์šฉํ•˜์˜€๋‹ค. ํ•ด๋‹น ๋…ธ๋“œ์™€ ์—ฐ๊ฒฐ๋œ ๊ฐ„์„ ์ด ์žˆ๋Š” ๋…ธ๋“œ๋ฅผ ๋Œ๋ฉด์„œ visited๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ ํ•ด๋‹น ๋…ธ๋“œ๋ฅผ ๋ฐฉ๋ฌธํ–ˆ๋Š”์ง€ ์ฒดํฌํ–ˆ๋‹ค.

    ๐Ÿฅ‚์ฝ”๋“œ

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
from collections import defaultdict

def dfs(node, visited, cnt):
    global answer
    if answer < cnt: answer = cnt
    for nxt_node in graph[node]:
        if not visited[nxt_node]:
            visited[nxt_node] = True
            dfs(nxt_node, visited, cnt + 1)
            visited[nxt_node] = False

T = int(input())
for tc in range(1, T + 1):
    n, m = map(int, input().split())
    graph = defaultdict(list)
    answer = 0
    if m==0: answer=1
    else:
        for _ in range(m):
            x, y = map(int, input().split())
            graph[x].append(y)
            graph[y].append(x)

        visited = [False] * (n + 1)
        visited[0] = True
        for node in range(1, n + 1):
            visited[node] = True
            dfs(node, visited, 1)
            visited[node] = False
    print('#{} {}'.format(tc, answer))
This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.