λ¬Έμ
https://www.acmicpc.net/problem/2206
νμ΄
# λ°±μ€ 2206λ² λ¬Έμ - λ²½ λΆμκ³ μ΄λνκΈ°
from collections import deque
n, m = map(int, input().split())
graph = []
for _ in range(n):
graph.append(list(map(int, input())))
dx, dy = [-1, 1, 0, 0], [0, 0, -1, 1]
def bfs(x, y):
visited = [[[0 for _ in range(2)] for _ in range(m)] for _ in range(n)]
visited[x][y][0] = 1
queue = deque()
queue.append((x, y, 0))
while queue:
x, y, wall = queue.popleft()
if (x, y) == (n-1, m-1):
return visited[x][y][wall]
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < n and 0 <= ny < m:
if graph[nx][ny] == 1 and wall == 0 and not visited[nx][ny][1]:
queue.append((nx, ny, 1))
visited[nx][ny][1] = visited[x][y][0] + 1
elif graph[nx][ny] == 0 and not visited[nx][ny][wall]:
queue.append((nx, ny, wall))
visited[nx][ny][wall] = visited[x][y][wall] + 1
return 0
result = bfs(0, 0)
if result:
print(result)
else:
print(-1)
μ΅λ¨κ²½λ‘λ₯Ό ꡬνλ BFS λ¬Έμ μ΄μ§λ§ 3μ°¨μ λ°°μ΄μ μ¬μ©ν΄μΌ νλ€.
'ποΈ Algorithm > π© λ°±μ€' μΉ΄ν κ³ λ¦¬μ λ€λ₯Έ κΈ
π© [λ°±μ€] [Python] [Silver1] 1991λ²_νΈλ¦¬ μν (0) | 2023.04.19 |
---|---|
π© [λ°±μ€] [Python] [Silver3] 15654λ²_Nκ³ΌM(5) (0) | 2023.04.18 |
π© [λ°±μ€] [Python] [Gold4] 1753λ²_μ΅λ¨κ²½λ‘ (0) | 2023.04.16 |
π© [λ°±μ€] [Python] [Gold4] 9663λ²_N-Queen (0) | 2023.04.15 |
π© [λ°±μ€] [Python] [Gold4] 5052λ²_μ νλ²νΈ λͺ©λ‘ (0) | 2023.04.14 |