ํŒŒ์ด์ฌ ์•Œ๊ณ ๋ฆฌ์ฆ˜

[์ด์ฝ”ํ…Œ Ch13-15] ํŠน์ • ๊ฑฐ๋ฆฌ์˜ ๋„์‹œ ์ฐพ๊ธฐ (BFS)

์€์ง„ 2022. 3. 22. 20:59

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ์„ค๋ช…

[์ด์ฝ”ํ…Œ Ch13-15] ํŠน์ • ๊ฑฐ๋ฆฌ์˜ ๋„์‹œ ์ฐพ๊ธฐ (BFS)
์ด์ฝ”ํ…Œ

โœ๏ธIdea Sketch

์‹œ๊ฐ„๋ณต์žก๋„

๊ทธ๋ž˜ํ”„๋ฅผ ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ํ•œ ๊ฒฝ์šฐ O(V + E)์ด๋‹ค.

  • BFS์—์„œ ๋ชจ๋“  ์ •์ ์„ ๋ฐฉ๋ฌธํ•œ๋‹ค. ํ•œ ๋ฒˆ ๋ฐฉ๋ฌธํ•œ ์ •์ ์€ ๋‹ค์‹œ ๋ฐฉ๋ฌธํ•˜์ง€ ์•Š๋Š”๋‹ค. (V = vertex = ์ •์ )

  • BFS์—์„œ ํ•œ ์ •์ ์„ ๋ฐฉ๋ฌธํ•  ๋•Œ๋งˆ๋‹ค ๊ฐ„์„ ์œผ๋กœ ์ธ์ ‘ํ•œ ์ •์ ์„ ๋ฐฉ๋ฌธํ•œ๋‹ค. ํ•œ ๋ฒˆ ์ง€๋‚˜๊ฐ„ ๊ฐ„์„ ์€ ๋‹ค์‹œ ์ง€๋‚˜๊ฐ€์ง€ ์•Š๋Š”๋‹ค. (E = edge = ๊ฐ„์„ )

  • ๋”ฐ๋ผ์„œ ๊ทธ๋ž˜ํ”„๋ฅผ ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ํ•œ ๊ฒฝ์šฐ, ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(V + E) ์ด๋‹ค.


์•Œ๊ณ ๋ฆฌ์ฆ˜ : BFS

๋„์‹œ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•ด์•ผ ํ•˜๋Š” ๋ฌธ์ œ์ด๋ฏ€๋กœ BFS ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ๊ตฌํ˜„ํ•˜๋ฉด ๋œ๋‹ค.


โœ๏ธ๋‚ด ์†Œ์Šค์ฝ”๋“œ

  • graph ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋ฅผ ๋งŒ๋“ค๊ณ  bfs ํ•จ์ˆ˜๋ฅผ ์‹คํ–‰ํ•œ๋‹ค.
  • ๋ฐฐ์—ด visited๋Š” ๋„์‹œ์˜ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ์ €์žฅํ•œ๋‹ค. ์ƒˆ๋กญ๊ฒŒ ๋ฐฉ๋ฌธํ•œ ๋„์‹œ y์˜ visited ๊ฐ’์€ ์ด์ „์— ๋ฐฉ๋ฌธํ•œ ๋„์‹œ x์˜ visited ๊ฐ’ + 1์ด๋‹ค.
  • ๋ฐฐ์—ด city๋Š” ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ K์ธ ๋„์‹œ์˜ ๋ฒˆํ˜ธ๋ฅผ ์ €์žฅํ•œ๋‹ค. ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ k์ธ ๊ฒฝ์šฐ city ๋ฐฐ์—ด์— ์ถ”๊ฐ€ํ•˜๊ณ , ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๊ฐ€ k๋ณด๋‹ค ํด ๊ฒฝ์šฐ์—๋Š” bfs ํ•จ์ˆ˜๋ฅผ ์ข…๋ฃŒํ•œ๋‹ค.


์ „์ฒด ์ฝ”๋“œ

  from collections import deque
  import sys
  si = sys.stdin.readline

  n, m, k, x = map(int, si().split())
  graph = [[] for _ in range(n + 1)]

  for _ in range(m):
    a, b = map(int, si().split())
    graph[a].append(b)


  def bfs(k, x):
    queue = deque([x])
    visited[x] = 0
    city = []

    while queue:
      x = queue.popleft()
      for y in graph[x]:
        if visited[y] == -1:
          visited[y] = visited[x] + 1
          queue.append(y)

          if visited[y] == k:
            city.append(y)
          elif visited[y] > k:
              return city

    return city


  visited = [-1] * (n + 1)
  city = bfs(k, x)

  if city:
    for x in sorted(city):
      print(x)
  else:
    print(-1)