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

[๋ฐฑ์ค€ 2178] ๋ฏธ๋กœ ํƒ์ƒ‰ (Python)

์€์ง„ 2021. 8. 3. 13:34

๐Ÿ‘ฉ๐Ÿปโ€๐Ÿ’ป๋ฌธ์ œ๋งํฌ

[๋ฐฑ์ค€ 2178] ๋ฏธ๋กœ ํƒ์ƒ‰ (Python)
๋ฐฑ์ค€


โœ๏ธIdea Sketch

2021-07-28

1. ๋ฐฑ์ค€ ์ž…๋ ฅ๊ฐ’ ์ฒ˜๋ฆฌ์—์„œ ํ—ค๋งธ๋˜ ๋ฌธ์ œ

  • sys.stdin.readline() : ํ•œ ์ค„์„ ์ž…๋ ฅ๋ฐ›์œผ๋ฉฐ, input()๊ณผ ๋น„์Šทํ•˜๋‹ค.
  • split() : ๋„์–ด์“ฐ๊ธฐ๋ฅผ ๊ธฐ์ค€์œผ๋กœ ์›์†Œ๋ฅผ ๋‚˜๋ˆˆ๋‹ค.
  • rstrip() : ์šฐ์ธก \n๋ฅผ ์ œ๊ฑฐํ•œ๋‹ค.
  • list(map(int, sys.stdin.readline().rstrip())) : ํ•œ ์ค„ ์ž…๋ ฅ๋ฐ›๊ณ , ์šฐ์ธก \n์„ ์ œ๊ฑฐํ•œ ํ›„, ๋ชจ๋“  ์›์†Œ๋ฅผ intํ˜•์œผ๋กœ ๋ณ€ํ™˜ํ•œ ๋ฐฐ์—ด์„ ์ƒ์„ฑํ•œ๋‹ค.
N, M = map(int, sys.stdin.readline().split())
graph = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(N)]

2. dx์™€ dy๋ฅผ ์ •์˜ํ•˜๊ณ , graph ๊ฒฝ๊ณ„๊ฐ’ ์ฒ˜๋ฆฌ

3. visited ์ƒ๋žต๊ฐ€๋Šฅ


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

2021-07-28

112ms ํ†ต๊ณผ, visited ์‚ฌ์šฉ

import sys
from collections import deque

N, M = map(int, sys.stdin.readline().split())
graph = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(N)]
visited = [[0 for _ in range(M)] for _ in range(N)]

def bfs(x, y):
  dx = [-1, 1, 0, 0]
  dy = [0, 0, -1, 1]
  queue = deque([(x, y)])
  visited[x][y] = 1
  while queue:
    x, y = queue.popleft()
    for i in range(4):
      nx = x + dx[i]
      ny = y + dy[i]
      if (-1<nx<N) and (-1<ny<M): #1 ๊ฒฝ๊ณ„๊ฐ’  [#1๋ถ€ํ„ฐ #3๊นŒ์ง€ ํ•œ ์ค„๋กœ ์ž‘์„ฑํ•  ๊ฒฝ์šฐ 124ms]
        if graph[nx][ny]: #2 ๋ฒฝ์ธ์ง€ ์•„๋‹Œ์ง€
            if not visited[nx][ny]: #3 ๋ฐฉ๋ฌธ์—ฌ๋ถ€ 
              queue.append((nx, ny))
              visited[nx][ny] = visited[x][y] + 1

  return visited[N-1][M-1]

print(bfs(0, 0))


124ms ํ†ต๊ณผ, visited ์ƒ๋žต

  • graph[nx][ny]๊ฐ€ 0์ด๋ฉด ๋ฒฝ
  • graph[nx][ny]๊ฐ€ 1์ด๋ฉด ์ฒ˜์Œ ๋ฐฉ๋ฌธํ•œ ๋…ธ๋“œ
  • graph[nx][ny]๊ฐ€ 1๋ณด๋‹ค ํฌ๋ฉด ๋ฐฉ๋ฌธํ•œ ์  ์žˆ๋Š” ๋…ธ๋“œ
import sys
from collections import deque

N, M = map(int, sys.stdin.readline().split())
graph = [list(map(int, sys.stdin.readline().rstrip())) for _ in range(N)]

def bfs(x, y):
  dx = [-1, 1, 0, 0]
  dy = [0, 0, -1, 1]
  queue = deque([(x, y)])
  while queue:
    x, y = queue.popleft()
    for i in range(4):
      nx = x + dx[i]
      ny = y + dy[i]
      if (-1<nx<N) and (-1<ny<M):
        if graph[nx][ny] == 1:
            queue.append((nx, ny))
            graph[nx][ny] = graph[x][y] + 1

  return graph[N-1][M-1]

print(bfs(0, 0))