ν°μ€ν 리 λ·°
728x90
λ°μν
λ¬Έμ
λ¬Έμ νμ΄
κ·Έλνλ₯Ό νμνλλ° μ΄λν μ μμ κ²½μ° λ²½ νλλ₯Ό λΆμκ³ νμμ μ΄μ΄κ° μ μλ€. μ¦, λ²½ νλλ₯Ό λΆμ κ²½μ° κ°μ₯ μ΅λ¨ κ²½λ‘λ‘ (N, M)μ λμ°©νλ κ²½μ°λ₯Ό λ°ννλ λ¬Έμ μ΄λ€. λ³΄ν΅ μ΅λ¨ 거리λ₯Ό ꡬν λ, 2μ°¨μ λ°°μ΄μ μμ±νμ¬ μ΄λν 거리λ₯Ό μ€μ²©μμΌλ©° μμΌλ‘ λμκ°λ©° λͺ©μ μ§μ λμ°©ν κ²½μ° νμμ μ’ λ£νλ€. λ¬Έμ μμλ λ²½μ λΆμ κ²½μ°μ λΆμμ§ μμ κ²½μ° 2κ°μ§μ κ²½μ°μ μκ° μ‘΄μ¬νκΈ°μ κΈ°μ‘΄μ 거리λ₯Ό μ€μ²©νλ λ°©μμ΄ μλ 3μ°¨μ λ°°μ΄μ ν΅ν΄ λΆμ κ²½μ°μ λν κ²½μ°μ μλ λ°λ‘ μ€μ²©μν¨λ€.
μ½λ
from sys import stdin
from collections import deque
def visitable(x, y, w):
return 0 <= x < n and 0 <= y < m and not visited[x][y][w]
def bfs(start):
q = deque([start])
dirs = ((-1, 0), (0, 1), (1, 0), (0, -1))
while q:
cur_x, cur_y, wall = q.popleft()
dist = visited[cur_x][cur_y][wall] + 1
if [cur_x, cur_y] == [n - 1, m - 1]:
return visited[cur_x][cur_y][wall]
for x, y in dirs:
next_x, next_y = cur_x + x, cur_y + y
if visitable(next_x, next_y, wall):
if not graph[next_x][next_y]:
visited[next_x][next_y][wall] = dist
q.append((next_x, next_y, wall))
elif not wall:
visited[next_x][next_y][not wall] = dist
q.append((next_x, next_y, not wall))
return -1
if __name__ == '__main__':
n, m = map(int, stdin.readline().split())
graph = [list(map(int, stdin.readline().strip())) for _ in range(n)]
visited = [[[0, 0] for _ in range(m)] for _ in range(n)]
visited[0][0] = [1, 1]
print(bfs((0, 0, 0)))
728x90
λ°μν
'π¨βπ» μ½λ©ν μ€νΈ > λ°±μ€' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
λ°±μ€: 16933 λ²½ λΆμκ³ μ΄λνκΈ° 3 (0) | 2020.08.04 |
---|---|
λ°±μ€: 14442 λ²½ λΆμκ³ μ΄λνκΈ° 2 (0) | 2020.08.03 |
λ°±μ€: 14502 μ°κ΅¬μ (0) | 2020.08.03 |
λ°±μ€: 16948 λ°μ€ λμ΄νΈ (0) | 2020.08.02 |
λ°±μ€: 9663 N-Queen (0) | 2020.08.01 |
λκΈ
κΈ λ³΄κ΄ν¨
μ΅κ·Όμ μ¬λΌμ¨ κΈ
μ΅κ·Όμ λ¬λ¦° λκΈ