728x90
import sys;input = sys.stdin.readline
from collections import deque as dq
n, m = map(int, input().split())
arr = [list(map(str, input().rstrip())) for _ in range(n)]
for i in range(n):
for j in range(m):
if arr[i][j] == '0':
sx, sy = i, j
arr[i][j] = '.'
def bfs(x, y):
q = dq([(x, y, 0, 0)])
visit = [[[0] * (1 << 6) for _ in range(50)] for _ in range(50)]
visit[x][y][0] = 1
while q:
x, y, cnt, key = q.popleft()
if arr[x][y] == '1':
print(cnt)
return
for dx, dy in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
nx, ny = x + dx, y + dy
if nx in range(n) and ny in range(m):
if not visit[nx][ny][key]:
if arr[nx][ny] in ['1', '.']:
visit[nx][ny][key] = 1
q.append((nx, ny, cnt + 1, key))
elif 'a' <= arr[nx][ny] <= 'f':
n_key = (1 << (ord(arr[nx][ny]) - ord('a'))) | key
visit[nx][ny][n_key] = 1
q.append((nx, ny, cnt + 1, n_key))
elif 'A' <= arr[nx][ny] <= 'F':
if key & (1 << (ord(arr[nx][ny]) - ord('A'))):
visit[nx][ny][key] = 1
q.append((nx, ny, cnt + 1, key))
print(-1)
return
bfs(sx, sy)
반응형
'백준 문제풀이 코드저장소 > Gold' 카테고리의 다른 글
Baekjoon 1197. 최소 스패닝 트리 / Python (0) | 2024.12.17 |
---|---|
Baekjoon 1167. 트리의 지름 / Python (0) | 2024.12.16 |
Baekjoon 32069. 가로등 / Python (0) | 2024.07.29 |
Baekjoon 11265. 끝나지 않는 파티 / Python (0) | 2024.07.28 |