๋ฐฑ์ค 24779๋ฒ ํ์ด์ฌ
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
## RecursionError๊ฐ ๋ฐ์ํ์ง ์๊ธฐ ์ํด ์ฌ๊ท์ ๊น์ด๋ฅผ ์ค์
## Pypy์ผ ๋๋ 10**5
## python ์ ์ถ์ผ๋๋ 10**6 ์ผ๋ก ์ค์
n, m, v = map(int,input().split())
graph = [[] for _ in range(n+1)]
# [[0] * (n+1) for _ in range(n+1)]
# ์์ ๊ฐ์ด ์ค์ ํ ๊ฒฝ์ฐ์ ๋ฉ๋ชจ๋ฆฌ์๋ฌ๊ฐ ๋ฐ์ํ๋ค.
# ๋ํ ์ค๋ฆ์ฐจ์์ผ๋ก ๋
ธ๋ ํ์ํ๊ธฐ ์ํด์ ๋
ธ๋์ ๊ฐ์ ๋ฃ์ด์ฃผ๋ ๋น๋ฐฐ์ด๋ก ์ค์
visited = [0 for _ in range(n+1)]
count = 1
for _ in range(m):
n1, n2 = map(int,input().split())
graph[n1].append(n2)
graph[n2].append(n1)
for nodes in graph: # ์ค๋ฆ์ฐจ์์ผ๋ก ๋
ธ๋๋ฅผ ํ์ํ๊ธฐ ์ํ ์ ๋ ฌ
nodes.sort()
def dfs(s):
global count
visited[s] = count
# ๋
ธ๋์ ๋ฐฉ๋ฌธ๊ธฐ๋ก์ผ๋ก ๊ธฐ๋กํ๋ค.
# ์ธ๋ฑ์ค ๊ฐ์ด ๋
ธ๋๋ฅผ ๋ํ๋
for i in graph[s]:
if (not visited[i]):
count += 1
dfs(i)
dfs(v)
for i in range(1, n+1):
print(visited[i])
python์์๋ ์ฌ๊ท๋ฅผ ์ฌ์ฉํ๋ ๊ฒ์ด ๋นํจ์จ์ ์
๋๋ค.
๊ทธ๋ ๊ธฐ์
์ฌ๊ท๋ฅผ ์ฌ์ฉํ์ง ์๊ณ DFS๋ฅผ ๊ตฌํํ๋ ๋ฐฉ๋ฒ์ chat-gpt์๊ฒ ๋ฌผ์ด๋ณด์์ต๋๋ค.
def dfs(graph, start):
stack = [start]
visited = set()
while stack:
current_node = stack.pop()
if current_node not in visited:
print(current_node)
visited.add(current_node)
# ํ์ฌ ๋
ธ๋์ ์ธ์ ๋
ธ๋๋ค์ ์คํ์ ์ถ๊ฐ
for neighbor in graph[current_node]:
if neighbor not in visited:
stack.append(neighbor)
# ๊ทธ๋ํ ์์ (์ธ์ ๋ฆฌ์คํธ ๋ฐฉ์)
graph = {
1: [2, 3],
2: [1, 4, 5],
3: [1, 6, 7],
4: [2],
5: [2],
6: [3],
7: [3]
}
dfs(graph, 1)
๊ทธ๋ํ์ ๊ณต๋ถ์ ๋ํ ํ์์ฑ์ ๋๋ผ๊ณ DFS๋ถํฐ ์ฐจ๊ทผ์ฐจ๊ทผ ๊ณต๋ถํด๋ณด๊ธฐ๋ก ํ์์ต๋๋ค.
ํ๋์์ DFS๋ฅผ ๊ณต๋ถํ๊ณ ์ผ์ ์์ค์ ๋ฌธ์ ๋ฅผ ํผ์ ํ ์ ์์ผ๋ฉด BFS๋ก ๋์ด๊ฐ ๊ณต๋ถ๋ฅผ ํด ๋ณผ ์์ ์
๋๋ค.