๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
์•Œ๊ณ ๋ฆฌ์ฆ˜/DFS BFS

[Python] ๋ฐฑ์ค€ 1260 DFS์™€ BFS

by JayAlex07 2023. 2. 6.

๐Ÿง‘‍๐Ÿ’ป [Python] ๋ฐฑ์ค€ 1260 DFS์™€ BFS

Silver 2 - DFS / BFS

DFS๋Š” ๊นŠ์ด ์šฐ์„ ์ด๋‹ค. ๋จผ์ € ํ•œ ์ชฝ์„ ์„ ํƒํ•ด์„œ, ํƒ์ƒ‰์„ ํ•˜๋Š” ๊ฒƒ์ด๋‹ค

BFS๋Š” ๋„“์ด ์šฐ์„  ํƒ์ƒ‰์ด๋‹ค. ์ฆ‰ ๋ถ€๋ชจ ๋…ธ๋“œ์— ์—ฌ๋Ÿฌ ์ž์‹ ๋…ธ๋“œ๊ฐ€ ์žˆ์œผ๋ฉด, ๋ฐ”๋กœ ์—ฐ๊ฒฐ๋˜์–ด ์žˆ๋Š” ์ž์‹ ๋…ธ๋“œ๋“ค ๋ถ€ํ„ฐ ํƒ์ƒ‰์„ ํ•œ๋‹ค

 

๋ฌธ์ œํ’€์ด

  • ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ–ˆ๋‹ค
  • ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค๊ณ , ๋ฆฌ์ŠคํŠธ ์•ˆ์— ์žˆ๋Š” ์š”์†Œ๋“ค์„ ์˜ค๋ฆ„์ฐจ์ˆœ์œผ๋กœ ์ •๋ ฌํ–ˆ๋‹ค (๋งŒ์•ฝ ๊ธธ์ด 2๊ฐœ ์ด์ƒ์ด๋ฉด, ์ˆซ์ž๊ฐ€ ์ž‘์€ ๊ณณ๋ถ€ํ„ฐ ํƒ์ƒ‰์„ ํ•œ๋‹ค)
  • DFS ๊ฐ™์€ ๊ฒฝ์šฐ, ์žฌ๊ท€๋ฅผ ์ด์šฉํ•œ๋‹ค
    • ์ฆ‰ DFS๋Š” ๋งŒ์•ฝ ๋ฐฉ๋ฌธ์„ ์•ˆ ํ•œ ๋…ธ๋“œ๊ฐ€ ์žˆ์œผ๋ฉด, ๊ทธ ๋…ธ๋“œ๋ฅผ ๋‹ค์‹œ DFS(V)๋ฅผ ํ•œ๋‹ค
    • ๋ฐฉ๋ฌธ์„ ํ–ˆ์œผ๋ฉด for๋ฌธ์€ ๋๊นŒ์ง€ ๋Œ์•„๊ฐˆ ๊ฒƒ์ด๋‹ค.
      • ์ฆ‰ for๋ฌธ์ด ๋๋‚ฌ๋‹ค๋Š” ๊ฒƒ์€, ์ด๋ฏธ ๋ชจ๋“  ๋…ธ๋“œ๋ฅผ ํ•œ๋ฒˆ์”ฉ ํƒ์ƒ‰์„ ํ–ˆ๋‹ค๋Š” ๊ฒƒ์ด๋‹ค
  • BFS ๊ฐ™์€ ๊ฒฝ์šฐ queue๋ฅผ ์ด์šฉํ–ˆ๋‹ค (DFS๋Š” pop์„ ํ•  ์ˆ˜๊ฐ€ ์—†๋‹ค. BFS, DFS ๋ชจ๋‘ ๊ฐ™์€ ๋ฐ์ดํ„ฐ๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค)
    • queue๋ฅผ ์ด์šฉํ•˜์—ฌ, ์ฃผ๋ณ€ ๋…ธ๋“œ๋“ค์„ ํƒ์ƒ‰ํ•˜๋Š” ๊ฒƒ์ด๋‹ค

 

์ฝ”๋“œ

from collections import deque

DFS_LIST = []
BFS_LIST = []

def dfs(V):
  dfs_visited[V] = 'V'
  DFS_LIST.append(V + 1)

  for i in graph[V]:
    if dfs_visited[i] != 'V':
      dfs(i)

  return DFS_LIST

def bfs(V):
  bfs_visited[V] = 'V'
  queue = deque([V])

  while queue:
    current = queue.popleft()
    BFS_LIST.append(current + 1)

    for cur in graph[current]:
      if bfs_visited[cur] != 'V':
        bfs_visited[cur] = 'V'
        queue.append(cur)

  return BFS_LIST


# N ์ •์ ์˜ ๊ฐœ์ˆ˜ / M ๊ฐ„์„ ์˜ ๊ฐœ์ˆ˜ / V ํƒ์ƒ‰ ์‹œ์ž‘
N, M, V = map(int, input().split())
V = V - 1
graph = [[] for _ in range(N)]
dfs_visited = [0] * (N)
bfs_visited = [0] * (N)

for _ in range(M):
  a, b = map(int, input().split())

  graph[a - 1].append(b - 1)
  graph[b - 1].append(a - 1)

for j in graph:
  j.sort()

print(graph)
print(' '.join(map(str, dfs(V))))
print(' '.join(map(str, bfs(V))))