λ¬Έμ
λ°±μ€ μ¨λΌμΈ μ μ§ - 5980λ²
νμ΄ κ³Όμ
μμμ§μ μμ λͺ©νμ§μ μ λλ¬νκΈ° μν μ΅μ μ΄λ νμλ₯Ό ꡬνλ BFS
λ¬Έμ μ
λλ€.
μ¬κΈ°μ μ£Όμν μ μ νΉμ μ§μ κ°μ μλ°©ν₯ ν¬νμ΄ μ‘΄μ¬νλ€λ κ²μ λλ€.
κ°κ°μ ν¬νμ λλ¬Έμ μνλ²³μΌλ‘ μ 곡λκΈ° λλ¬Έμ ν΄μ ν
μ΄λΈ
μ μ΄μ©ν΄μ κ° ν¬νμ μ 보λ₯Ό κ΄λ¦¬ν©λλ€.
λν μ€λ³΅ λ°©λ¬Έμ λ°©μ§νκΈ° μν΄μ visit
μ 체ν¬ν λ ν¬νμ μμΉλ μ€λ³΅ λ°©λ¬Έμ νμ©ν΄μΌ νλ€λ μ μ μ£Όμν©λλ€.
μ΄λ κ² νμ§ μμΌλ©΄ ν¬νμ νλ²λ°μ μ¬μ©νμ§ λͺ»νλ μν©μ΄ λ°μνμ¬ νμν λ μ¬μ©ν μ μκΈ° λλ¬Έμ λλ€.
μ΄λ‘μΈν΄ λ€μκ³Ό κ°μ μμμμ λ¬Έμ κ° λ°μν μ μμ΅λλ€.
######
#.WB##
#.####
=B@W##
######
μ½λ
import sys
from collections import deque
N, M = list(map(int, sys.stdin.readline().split()))
board = [list(sys.stdin.readline().strip()) for _ in range(N)]
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def pre_processing():
start, goal = [], []
slides = {}
for x in range(N):
for y in range(M):
if board[x][y] == '@':
start = [x, y]
if board[x][y] == '=':
goal = [x, y]
if 'A' <= board[x][y] <= 'Z':
if board[x][y] not in slides:
slides[board[x][y]] = [[x, y]]
else:
slides[board[x][y]].append([x, y])
return start, goal, slides
def bfs(start, goal, slides):
q = deque()
visit = [[0] * M for _ in range(N)]
q.append([*start, 0])
visit[start[0]][start[1]] = 1
while q:
x, y, cost = q.popleft()
if [x, y] == goal:
return cost
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
if not board[nx][ny] == '#' and not visit[nx][ny]:
if 'A' <= board[nx][ny] <= 'Z':
slide = slides[board[nx][ny]]
if [nx, ny] == slide[0]:
q.append([*slide[1], cost + 1])
else:
q.append([*slide[0], cost + 1])
else:
if not visit[nx][ny]:
visit[nx][ny] = 1
q.append([nx, ny, cost + 1])
def solution():
start, goal, slides = pre_processing()
answer = bfs(start, goal, slides)
return answer
print(solution())
'π algorithm > boj' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
BOJ 4889 - μμ μ μΈ λ¬Έμμ΄ (0) | 2021.06.07 |
---|---|
BOJ 4811 - μμ½ (0) | 2021.06.07 |
BOJ 1240 - λ Έλμ¬μ΄μ 거리 (0) | 2021.06.07 |
BOJ 11265 - λλμ§ μλ νν° (0) | 2021.06.04 |
BOJ 10472 - μμλ€μ§κΈ° (0) | 2021.04.18 |
π¬ λκΈ