3차원배열 받는법좀 까먹지말자,,
while True:
# l, r, c 입력
l, r, c = map(int, input().split())
# 종료조건
if l == 0 and r == 0 and c == 0:
break
# building
building = [
[[0 for _ in range(c)] for _ in range(r)] for _ in range(l)
]
# building 입력받기
for h in range(l):
for i in range(r):
block = input()
for j in range(c):
# 시작 위치 저장
if block[j] == 'S':
sh, sx, sy = h, i, j
# 끝 위치 저장
if block[j] == 'E':
eh, ex, ey = h, i, j
# 벽 세워주기
if block[j] == '#':
building[h][i][j] = 1
input()
# 함수들
# in_range(h, x, y)
def in_range(h, x, y):
return 0 <= h < l and 0 <= x < r and 0 <= y < c
# check(h, x, y)
def check(h, x, y):
# 범위 내에 있고, 방문한 적 없고, 벽이 아니면 됨
return in_range(h, x, y) and not visited[h][x][y] and not building[h][x][y]
# bfs()
def bfs():
while q:
h, x, y = q.popleft()
# 동 서 남 북 상 하
dhs, dxs, dys = [-1, 1, 0, 0, 0, 0], [0, 0, -1, 1, 0, 0], [0, 0, 0, 0, -1, 1]
for dh, dx, dy in zip(dhs, dxs, dys):
nh, nx, ny = h + dh, x + dx, y + dy
# 다음 위치로 갈 수 있으면
if check(nh, nx, ny):
# 큐에 넣어주고
q.append((nh, nx, ny))
# 방문 처리 해 주고
visited[nh][nx][ny] = 1
# step 배열 관리
step[nh][nx][ny] = step[h][x][y] + 1
# 설계
# 큐 사용준비
from collections import deque
q = deque()
# visited
visited = [
[[0 for _ in range(c)] for _ in range(r)] for _ in range(l)
]
# step
step = [
[[0 for _ in range(c)] for _ in range(r)] for _ in range(l)
]
# 큐에 넣어주고
q.append((sh, sx, sy))
# 방문 처리 해 주고
visited[sh][sx][sy] = 1
# bfs 돌려주기
bfs()
# 끝 지점에 도달하지 못했으면,
if not visited[eh][ex][ey]:
# 실패 처리 후
print('Trapped!')
# 도달했으면.
else:
# 걸린 시간 측정
spended_time = step[eh][ex][ey]
# 출력
print('Escaped in %d minute(s).' % (spended_time))'Algorithm(BOJ, Python) > BFS&DFS' 카테고리의 다른 글
| [백준_22352] 항체인식 python (1) | 2022.09.13 |
|---|---|
| [백준_1245] 농장관리 python (0) | 2022.09.11 |
| [백준_17836] 공주님을 구해라 python (2) | 2022.09.09 |
| [백준_2589] 보물섬 python (0) | 2022.09.05 |
| [백준_17141] 연구소 2 python (0) | 2022.09.02 |