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

[์ด์ฝ”ํ…Œ Ch17-40] ์ˆจ๋ฐ”๊ผญ์งˆ

์€์ง„ 2022. 5. 10. 18:18

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

[์ด์ฝ”ํ…Œ Ch17-40] ์ˆจ๋ฐ”๊ผญ์งˆ
์ด์ฝ”ํ…Œ

โœ๏ธIdea Sketch

๋ฌธ์ œ์š”์•ฝ

์ตœ๋‹จ๊ฒฝ๋กœ ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค.
๋ฌธ์ œ์—์„œ "์—ฌ๊ธฐ์„œ ๊ฑฐ๋ฆฌ๋ผ ํ•จ์€ ์ง€๋‚˜์•ผ ํ•˜๋Š” ๊ธธ์˜ ์ตœ์†Œ ๊ฐœ์ˆ˜์ด๋‹ค. " ๋ผ๊ณ  ๋ช…์‹œํ–ˆ๋‹ค. ๋”ฐ๋ผ์„œ ์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ๊ตฌํ•˜๋ฉด ๋œ๋‹ค.

์ถœ๋ฐœ ํ—›๊ฐ„์€ 1๋ฒˆ์ด๋‹ค.
1๋ฒˆ ํ—›๊ฐ„์—์„œ x๋ฒˆ ํ—›๊ฐ„๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ๋ชจ๋‘ ๊ตฌํ•˜๊ณ , ๊ทธ ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ์ฐพ์•„์•ผ ํ•œ๋‹ค.
๊ฐ€์ค‘์น˜๊ฐ€ ์—†๊ณ  ๋ชจ๋“  ํ—›๊ฐ„์„ ํƒ์ƒ‰ํ•ด์•ผ ํ•œ๋‹ค.


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

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

BFS๋Š” ๋ชจ๋“  ์ •์ ์„ ๋ฐฉ๋ฌธํ•˜๋ฏ€๋กœ O(V)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง„๋‹ค. ์ด ๋•Œ ํ•œ ์ •์ ์„ ๋ฐฉ๋ฌธํ•  ๋•Œ๋งˆ๋‹ค ๊ฐ„์„ ์„ ํ†ตํ•ด ์ธ์ ‘ํ•œ ์ •์ ์„ ๋ฐฉ๋ฌธํ•œ๋‹ค. ๋ชจ๋“  ๊ฐ„์„ ๋„ ๋ฐฉ๋ฌธํ•˜๋ฏ€๋กœ O(E)์˜ ์‹œ๊ฐ„๋ณต์žก๋„๋ฅผ ๊ฐ€์ง„๋‹ค. ๋”ฐ๋ผ์„œ BFS์˜ ์ด ์‹œ๊ฐ„๋ณต์žก๋„๋Š” ๋‘˜์„ ํ•ฉํ•œ O(V + E)์ด๋‹ค.


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

์ตœ๋‹จ๊ฒฝ๋กœ๋ฅผ ๋ชจ๋‘ ๊ตฌํ•˜๊ณ , ๊ทธ ์ค‘ ๊ฐ€์žฅ ํฐ ๊ฐ’์„ ์ฐพ๋Š” ๋ฌธ์ œ์ด๋‹ค. ๋ชจ๋“  ์ •์ ์„ ํƒ์ƒ‰ํ•ด์•ผ ํ•˜๊ณ  ๊ฐ€์ค‘์น˜๊ฐ€ ์—†๋‹ค. ๋”ฐ๋ผ์„œ BFS ๋„ˆ๋น„์šฐ์„ ํƒ์ƒ‰ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ ๊ตฌํ˜„ํ•œ๋‹ค.


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

  • graph์„ ์ธ์ ‘๋ฆฌ์ŠคํŠธ๋กœ ๊ตฌํ˜„ํ•œ๋‹ค.
  • visited์— 1๋ฒˆ ํ—›๊ฐ„์—์„œ์˜ ๊ฑฐ๋ฆฌ๋ฅผ ์ €์žฅํ•œ๋‹ค. ์ดˆ๊ธฐ๊ฐ’์€ -1์ด๊ณ , ์ถœ๋ฐœ์ง€ 1๋ฒˆ ํ—›๊ฐ„์˜ visited ์ดˆ๊ธฐ๊ฐ’์€ 0์ด๋‹ค. ์ธ์ ‘ ํ—›๊ฐ„ y๋ฅผ ๋ฐฉ๋ฌธํ•  ๋•Œ๋งˆ๋‹ค ์ด์ „ ํ—›๊ฐ„ x์˜ visited ๊ฐ’์— 1์„ ๋”ํ•œ ๊ฐ’์„ ์ €์žฅํ•œ๋‹ค.
  • ์ตœ์ข…์ ์œผ๋กœ ์ˆจ์–ด์•ผ ํ•˜๋Š” ํ—›๊ฐ„ ๋ฒˆํ˜ธ num, ๊ทธ ํ—›๊ฐ„๊นŒ์ง€์˜ ๊ฑฐ๋ฆฌ leng, ๊ทธ ํ—›๊ฐ„๊ณผ ๊ฐ™์€ ๊ฑฐ๋ฆฌ๋ฅผ ๊ฐ–๋Š” ํ—›๊ฐ„์˜ ๊ฐœ์ˆ˜ cnt๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. visited๋ฅผ ๋ฐ”ํƒ•์œผ๋กœ ๊ณ„์‚ฐํ•œ๋‹ค.


์ „์ฒด ์ฝ”๋“œ

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

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

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

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

  bfs(1)

  leng = max(visited)
  num = visited.index(leng)
  cnt = visited.count(leng)

  print(num, leng, cnt)