[ 2023-07-19 ๐Ÿ„ TIL ]

Burkeyยท2023๋…„ 7์›” 19์ผ
0

TIL

๋ชฉ๋ก ๋ณด๊ธฐ
123/157

๋ฐฑ์ค€ 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๋กœ ๋„˜์–ด๊ฐ€ ๊ณต๋ถ€๋ฅผ ํ•ด ๋ณผ ์˜ˆ์ •์ž…๋‹ˆ๋‹ค.

profile
์Šคํƒฏ ์˜ฌ๋ฆฌ๋Š” ์ค‘

0๊ฐœ์˜ ๋Œ“๊ธ€