[SWEA] 2814. ์ต์ฅ ๊ฒฝ๋ก(python)
๐๋ฌธ์
๐ช์์ด๋์ด
- ๊ทธ๋ํ ๊ฐ์ ํ์
2์ฐจ์๋ฐฐ์ด๋ก ํ์ํ ์ ๋ ์์ง๋ง defaultdict์ด ๋ ํธํด์ ๋์ ๋๋ฆฌ๋ฅผ ์ฌ์ฉํ์๋ค. key๋ ๋ ธ๋๋ฒํธ, value๋ ์ฐ๊ฒฐ๋ ๋ ธ๋์ ๋ฒํธ - ๋
ธ๋ ๋ฐฉ๋ฌธ
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.