๐ง๐ป [Python] ๋ฐฑ์ค 24482 ์๊ณ ๋ฆฌ์ฆ ์์
Silver 2 - DFS
DFS ๋ฌธ์ ์ด๋ค
๊น์ด ์ฐ์ ํ์์ผ๋ก, ํ์์ ํ ๋๋ง๋ค 1์ฉ ๋ํด์ฃผ๋ฉด ๋๋ค
- ์ฐ๊ฒฐ์ด ์์ ์ ๋์ด ์์ ๋์๋ -1 ์ด๋ค
- ๋ด๋ฆผ์ฐจ์
๋ฌธ์ ํ์ด
- DFS ์ฝ๋๋ฅผ ์ง๋ฉด ๋๋ค
์ฝ๋
import sys
sys.setrecursionlimit(10 ** 6)
input = sys.stdin.readline
def dfs(start, count):
visited[start] = count
for cur in graph[start]:
if visited[cur] == -1:
dfs(cur, count + 1)
N, M, start = map(int, input().split())
visited = [-1] * (N + 1)
graph = [[] for _ in range(N + 1)]
for _ in range(M):
a, b = map(int, input().split())
graph[a].append(b)
graph[b].append(a)
for node in graph:
node.sort(reverse=True)
stack = []
dfs(start, 0)
for i in range(1, len(visited)):
print(visited[i])
'์๊ณ ๋ฆฌ์ฆ > DFS BFS' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[Python] ๋ฐฑ์ค 1967 ํธ๋ฆฌ์ ์ง๋ฆ (0) | 2023.02.16 |
---|---|
[Python] ๋ฐฑ์ค 1520 ๋ด๋ฆฌ๋ง๊ธธ (0) | 2023.02.15 |
[Python] ๋ฐฑ์ค 7569 ํ ๋งํ (0) | 2023.02.13 |
[Python] ๋ฐฑ์ค 7576 ํ ๋งํ (0) | 2023.02.13 |
[Python] ๋ฐฑ์ค 24481 ์๊ณ ๋ฆฌ์ฆ ์์ DFS (์ฌ๊ท!!!) (0) | 2023.02.11 |