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

[์ด์ฝ”ํ…Œ Ch5-4] ๋ฏธ๋กœํƒˆ์ถœ (BFS)

์€์ง„ 2022. 1. 9. 21:53

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

[์ด์ฝ”ํ…Œ Ch5-4] ๋ฏธ๋กœํƒˆ์ถœ (BFS)
์ด์ฝ”ํ…Œ

N x M ํฌ๊ธฐ์˜ ์ง์‚ฌ๊ฐํ˜• ํ˜•ํƒœ์˜ ๋ฏธ๋กœ์— ์—ฌ๋Ÿฌ ๋งˆ๋ฆฌ์˜ ๊ดด๋ฌผ์ด ์žˆ์–ด ์ด๋ฅผ ํ”ผํ•ด ํƒˆ์ถœํ•ด์•ผ ํ•œ๋‹ค. ํ˜„์žฌ ์œ„์น˜๋Š” (1, 1)์ด๊ณ  ๋ฏธ๋กœ์˜ ์ถœ๊ตฌ๋Š” (N,M)์˜ ์œ„์น˜์— ์กด์žฌํ•˜๋ฉฐ ํ•œ ๋ฒˆ์— ํ•œ ์นธ์”ฉ ์ด๋™ํ•  ์ˆ˜ ์žˆ๋‹ค. ๊ดด๋ฌผ์ด ์žˆ๋Š” ๋ถ€๋ถ„์€ 0์œผ๋กœ, ๊ดด๋ฌผ์ด ์—†๋Š” ๋ถ€๋ถ„์€ 1๋กœ ํ‘œ์‹œ๋˜์–ด ์žˆ๋‹ค. ๋ฏธ๋กœ๋Š” ๋ฐ˜๋“œ์‹œ ํƒˆ์ถœํ•  ์ˆ˜ ์žˆ๋Š” ํ˜•ํƒœ๋กœ ์ œ์‹œ๋œ๋‹ค. ํƒˆ์ถœํ•˜๊ธฐ ์œ„ํ•ด ์›€์ง์—ฌ์•ผ ํ•˜๋Š” ์ตœ์†Œ ์นธ์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜๋ผ. ์นธ์„ ์…€ ๋•Œ๋Š” ์‹œ์ž‘ ์นธ๊ณผ ๋งˆ์ง€๋ง‰ ์นธ์„ ๋ชจ๋‘ ํฌํ•จํ•ด์„œ ๊ณ„์‚ฐํ•œ๋‹ค.


์ž…๋ ฅ

  • ์ฒซ์งธ ์ค„์— ๋‘ ์ •์ˆ˜ N, M(4 <= N, M <= 200)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‹ค์Œ N๊ฐœ์˜ ์ค„์—๋Š” ๊ฐ๊ฐ M๊ฐœ์˜ ์ •์ˆ˜(0ํ˜น์€ 1)๋กœ ๋ฏธ๋กœ์˜ ์ •๋ณด๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๊ฐ๊ฐ์˜ ์ˆ˜๋“ค์€ ๊ณต๋ฐฑ ์—†์ด๋ถ™์–ด์„œ ์ž…๋ ฅ์œผ๋กœ ์ œ์‹œ๋œ๋‹ค. ๋˜ํ•œ ์‹œ์ž‘ ์นธ๊ณผ ๋งˆ์ง€๋ง‰ ์นธ์€ ํ•ญ์ƒ 1์ด๋‹ค.

์ถœ๋ ฅ

  • ์ฒซ์งธ ์ค„์— ์ตœ์†Œ ์ด๋™ ์นธ์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.


์ž…๋ ฅ ์˜ˆ์‹œ
5 6
101010
111111
000001
111111
111111

์ถœ๋ ฅ ์˜ˆ์‹œ
10


โœ๏ธIdea Sketch

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


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

2์ฐจ์› ๋งต์—์„œ ์ƒํ•˜์ขŒ์šฐ 4๋ฐฉํ–ฅ์œผ๋กœ ์›€์ง์ผ ์ˆ˜ ์žˆ๊ณ , ํŠน์ • ๋ชฉํ‘œ์ •์ ๊นŒ์ง€์˜ ์ตœ๋‹จ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•  ๋•Œ, BFS ํƒ์ƒ‰ ๋ฐฉ๋ฒ•์„ ์‚ฌ์šฉํ•˜๊ฒŒ ๋  ๊ฒฝ์šฐ ์‹œ๊ฐ„๋ณต์žก๋„๋Š” O(NM)์ด๋‹ค. ์ •์ ์˜ ๊ฐœ์ˆ˜๊ฐ€ O(NM)๊ฐœ์ด๊ณ , ๊ฐ ์ •์ ์—์„œ ์—ฐ๊ฒฐ๋œ ๊ฐ„์„ ์ด 4๊ฐœ์”ฉ์ด๋‹ˆ๊นŒ ๊ฐ„์„ ์˜ ์ด ๊ฐœ์ˆ˜๋Š” O(4NM)์ธ๋ฐ, ์ƒ์ˆ˜๋ฐฐ๋Š” ๋ฌด์‹œํ•  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ๋˜‘๊ฐ™์ด O(NM)์œผ๋กœ ์“ธ ์ˆ˜ ์žˆ๋‹ค. BFS ํƒ์ƒ‰ ๊ณผ์ •์—์„œ ์ •์ ์„ O(NM)๊ฐœ ๋ณด๊ณ  ๊ฐ„์„ ๋„ O(NM)๊ฐœ ๋ณด๋‹ˆ O(NM+NM) = O(2NM)์ธ๋ฐ, ์—ญ์‹œ ์ƒ์ˆ˜๋ฐฐ๋Š” ๋ฌด์‹œํ•  ์ˆ˜ ์žˆ์œผ๋‹ˆ O(NM)์ด๋‹ค.

๋ฐฑ์ค€ ์ฐธ๊ณ  ์‚ฌ์ดํŠธ

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

  • ์ถœ๋ฐœ์ง€ (0, 0)์—์„œ ์ถœ๋ฐœํ•˜์—ฌ ๋ชฉ์ ์ง€ (n-1, m-1)๊นŒ์ง€ ๋ฏธ๋กœ๋ฅผ ํƒ์ƒ‰ํ•œ๋‹ค.
  • ์ด๋™ํ•˜๋ ค๋Š” ์ขŒํ‘œ (nx, ny)์˜ ์ขŒํ‘œ๊ฐ’์ด 1๋กœ ๊ดด๋ฌผ์ด ์—†๋Š” ๊ฒฝ์šฐ, ํ•ด๋‹น ์ขŒํ‘œ๊ฐ’์„ ๊ฐฑ์‹ ํ•˜๊ณ  queue์— ์ขŒํ‘œ๋ฅผ ์ถ”๊ฐ€ํ•œ๋‹ค.
  • ์ตœ์ข…์ ์œผ๋กœ ๋ชฉ์ ์ง€ (n-1, m-1)์˜ ์ขŒํ‘œ๊ฐ’์„ ๋ฆฌํ„ดํ•œ๋‹ค.
  from collections import deque
  import sys
  si = sys.stdin.readline


  def bfs():
    queue = deque([[0, 0]])

    while queue:
      x, y = queue.popleft()
      for dx, dy in (-1, 0), (1, 0), (0, -1), (0, 1):
        nx, ny = x + dx, y + dy
        if (0 <= nx < n) and (0 <= ny < m) and graph[nx][ny] == 1:
          graph[nx][ny] = graph[x][y] + 1
          queue.append([nx, ny])

    return graph[n-1][m-1]


  n,m = map(int, si().split())
  graph = [list(map(int, si().rstrip())) for _ in range(n)]

  print(bfs())