728x90
반응형
기본적인 BFS 문제이다. B에서 C로 가는 최단거리의 길이를 출력해주면 된다.
from collections import deque
def bfs(y, x):
q = deque()
q.append((y, x))
graph[y][x] = 0
while q:
y, x = q.popleft()
for dy, dx in d:
Y, X = y+dy, x+dx
if (0 <= Y < R) and (0 <= X < C) and graph[Y][X] in ['.', 'C']:
if graph[Y][X] == 'C':
return graph[y][x]+1
q.append((Y, X))
graph[Y][X] = graph[y][x]+1
R, C = map(int, input().split())
graph = [list(input()) for _ in range(R)]
d = [(-1, 0), (1, 0), (0, -1), (0, 1)]
for i in range(R):
for j in range(C):
if graph[i][j] == 'B':
print(bfs(i, j))
break
728x90
반응형
'Agorithm > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 6080번 Bad Grass(python) (0) | 2021.03.17 |
---|---|
백준 알고리즘 20540번 연길이의 이상형(python) (0) | 2021.03.17 |
백준 알고리즘 18422번 Emacs(python) (0) | 2021.03.17 |
백준 알고리즘 13746번 Islands(python) (0) | 2021.03.17 |
백준 알고리즘 10204번 Neighborhoods in Graphs(python) (0) | 2021.03.16 |