λ¬Έμ
λ°±μ€ μ¨λΌμΈ μ μ§ - 14923λ²
νμ΄ κ³Όμ
μμ μ§μ μμ λͺ©ν μ§μ μ λλ¬νλ μ΅λ¨ κ²½λ‘λ₯Ό μ°Ύλ BFS
λ¬Έμ μ
λλ€.
λ¨ λ²½μ΄ μ‘΄μ¬ν κ²½μ° 1νμ νν΄μ λ²½μ λΆμκ³ μ΄λν μ μκΈ° λλ¬Έμ μν 곡κ°μ λ€μκ³Ό κ°μ΄ μ μν©λλ€.
visit[x][y][magic] : (x, y) μ§μ μ λ¨μ λ§λ²μ νμ magic μ μ΄μ©νμ¬ λλ¬ ν κ²½μ°κ° μλμ§
μ΄ν λͺ©ν μ§μ μ λλ¬νλ©΄ 거리 λ°μ©μ λ°ννλ©΄ λ©λλ€.
μ½λ
import sys
from collections import deque
N, M = list(map(int, sys.stdin.readline().split()))
Hx, Hy = list(map(int, sys.stdin.readline().split()))
Ex, Ey = list(map(int, sys.stdin.readline().split()))
board = [list(map(int, sys.stdin.readline().split())) for _ in range(N)]
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def bfs():
q = deque()
visit = [[[0] * 2 for _ in range(M)] for _ in range(N)]
q.append([Hx - 1, Hy - 1, 1, 0])
visit[Hx - 1][Hy - 1][1] = 1
while q:
x, y, magic, cost = q.popleft()
if [x, y] == [Ex - 1, Ey - 1]:
return cost
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < N and 0 <= ny < M:
if visit[nx][ny][magic]:
continue
if magic and board[nx][ny]:
visit[nx][ny][0] = 1
q.append([nx, ny, 0, cost + 1])
elif not board[nx][ny]:
visit[nx][ny][magic] = 1
q.append([nx, ny, magic, cost + 1])
return -1
def solution():
answer = bfs()
return answer
print(solution())
λ°μν
'π algorithm > boj' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
BOJ 2096 - λ΄λ €κ°κΈ° (0) | 2021.03.18 |
---|---|
BOJ 14716 - νμλ§ (0) | 2021.03.18 |
BOJ 17406 - λ°°μ΄ λ리기 4 (0) | 2021.03.18 |
BOJ 1543 - λ¬Έμ κ²μ (0) | 2021.03.18 |
BOJ 11403 - κ²½λ‘ μ°ΎκΈ° (0) | 2021.03.18 |
π¬ λκΈ