๐ง๐ป [Python] ๋ฐฑ์ค 24481 ์๊ณ ๋ฆฌ์ฆ ์์ DFS (์ฌ๊ท!!!)
Silver 2 - DFS
์์ ๊ธฐ์ค์์ ๊ฐ ๋ ธ๋๊น์ง ์ผ๋ง๋ ๊ฑธ๋ฆฌ๋์ง ์ฐพ๋๋ค
๋ฌธ์ ํ์ด
- ์ฌ๊ท๋ฅผ ์ด์ฉํ์ฌ DFS๋ฅผ ์คํํ๋ค
sys.setrecursionlimit(10 ** 6)
input=sys.stdin.readline
- ์ฌ๊ท๋ฅผ ์ ํํด์ฃผ๋ ์์ด๋ค (์ฝ๋ฉ ํ ์คํธ์์ ์ฌ๊ท๋ฅผ ์ฌ์ฉํ ๋์ ๊ผญ ํ์ํ๋ค)
์ฝ๋
import sys
sys.setrecursionlimit(10 ** 6)
input=sys.stdin.readline
def dfs(start, count):
result[start] = count
for num in tree[start]:
if result[num] == -1:
dfs(num, count + 1)
n, m, r = map(int, input().split())
tree = [[] for _ in range(n + 1)]
result = [-1] * (n+1)
for _ in range(m):
a, b = map(int, input().split())
tree[a].append(b)
tree[b].append(a)
for t in tree:
t.sort()
dfs(r, 0)
for i in range(1, n+1):
print(result[i])
'์๊ณ ๋ฆฌ์ฆ > DFS BFS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] ๋ฐฑ์ค 7569 ํ ๋งํ (0) | 2023.02.13 |
---|---|
[Python] ๋ฐฑ์ค 7576 ํ ๋งํ (0) | 2023.02.13 |
[Python] ๋ฐฑ์ค 2644 ์ด์๊ณ์ฐ (0) | 2023.02.09 |
[Python] ๋ฐฑ์ค 1388 ๋ฐ๋ฅ ์ฅ์ (4) | 2023.02.08 |
[Python] ๋ฐฑ์ค 1260 DFS์ BFS (0) | 2023.02.06 |