BOJ - 6189 - Munching
Updated:
import sys
from collections import deque
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def BFS(sx, sy, ex, ey, matrix, R, C):
dq = deque()
dq.append((sx, sy, 0))
visit = [[False for _ in range(C)] for _ in range(R)]
visit[sx][sy] = True
while dq:
x, y, w = dq.popleft()
if x == ex and y == ey:
return w
for k in range(4):
nx, ny = x + dx[k], y + dy[k]
if 0 <= nx < R and 0 <= ny < C:
if visit[nx][ny] == False and (matrix[nx][ny] == '.' or matrix[nx][ny] == 'C'):
visit[nx][ny] = True
dq.append((nx, ny, w + 1))
return -1
def solution():
R, C = map(int, sys.stdin.readline().split())
matrix = []
for _ in range(R):
matrix.append(list(sys.stdin.readline().strip()))
sx, sy, dx, dy = 0, 0, 0, 0
for i in range(R):
for j in range(C):
if matrix[i][j] == 'B':
sx, sy = i, j
elif matrix[i][j] == 'C':
dx, dy = i, j
print(BFS(sx, sy, dx, dy, matrix, R, C))
solution()
https://www.acmicpc.net/problem/6189
Leave a comment