728x90
반응형
기본적인 BFS 문제이다.
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 < N) and (0 <= X < M):
if graph[Y][X] == 'H':
return graph[y][x]+1
if graph[Y][X] == '.':
q.append((Y, X))
graph[Y][X] = graph[y][x]+1
M, N = map(int, input().split())
graph = [list(input()) for _ in range(N)]
d = [(-2, -1), (-2, 1), (2, -1), (2, 1), (-1, -2), (1, -2), (-1, 2), (1, 2)]
for i in range(N):
for j in range(M):
if graph[i][j] == 'K':
print(bfs(i, j))
break
728x90
반응형
'Agorithm > 백준 알고리즘' 카테고리의 다른 글
백준 알고리즘 6798번 Knight Hop(python) (0) | 2021.03.18 |
---|---|
백준 알고리즘 6229번 Bronze Lilypad Pond(python) (0) | 2021.03.18 |
백준 알고리즘 17266번 어두운 굴다리(python) (0) | 2021.03.18 |
백준 알고리즘 17219번 비밀번호 찾기(python) (0) | 2021.03.18 |
백준 알고리즘 11727번 2×n 타일링 2(python) (0) | 2021.03.18 |