Coding Test/백준(Python)
[백준/Python] 6593번(BFS)_상범빌딩
syunze
2023. 9. 5. 14:14
📌문제 유형
BFS (골드 Lv.5)
📌문제
📌나의 문제풀이
- break 위치 주의하기
- 처음에 x,y,z for문에 break 걸어놨더니 틀렸음(당연,,,,break걸어두면 x,y,z 0,0,0인 경우 밖에 못찾음)
from collections import deque
while True:
l,r,c = map(int,input().split())
if l == 0 and r == 0 and c == 0:
break
maps = []
for _ in range(l):
floor = []
for _ in range(r+1):
floor.append(list(map(str,input())))
floor = floor[:-1][:]
maps.append(floor)
visited = [[[0 for _ in range(c)] for _ in range(r)] for _ in range(l)]
ans = -1
for x in range(l):
for y in range(r):
for z in range(c):
if maps[x][y][z] == 'S':
q = deque([])
q.append((x,y,z))
visited[x][y][z] = 1
while q:
x_,y_,z_ = q.popleft()
if maps[x_][y_][z_] == 'E':
ans = visited[x_][y_][z_]
break
dx = [1,-1,0,0,0,0] # 순서대로 위,아래, 동, 서, 남, 북
dy = [0,0,1,-1,0,0]
dz = [0,0,0,0,-1,1]
for i in range(6):
nx = x_ + dx[i]
ny = y_ + dy[i]
nz = z_ + dz[i]
if 0 <= nx < l and 0 <= ny < r and 0 <= nz < c:
if maps[nx][ny][nz] == '.' and visited[nx][ny][nz] == 0:
visited[nx][ny][nz] = visited[x_][y_][z_] + 1
q.append((nx,ny,nz))
if maps[nx][ny][nz] == 'E' and visited[nx][ny][nz] == 0:
visited[nx][ny][nz] = visited[x_][y_][z_]
q.append((nx,ny,nz))
if ans != -1:
print('Escaped in {0} minute(s).'.format(ans))
else:
print('Trapped!')
📌 다른사람의 문제풀이
import sys
from collections import deque
input = sys.stdin.readline
dz = (1, -1, 0, 0, 0, 0)
dx = (0, 0, 1, -1, 0, 0)
dy = (0, 0, 0, 0, 1, -1)
while True:
l, r, c = map(int, input().split())
if l == 0 and r == 0 and c == 0:
break
board = []
visited = [[[False] * c for _ in range(r)] for _ in range(l)]
for _ in range(l):
board.append([list(input().strip()) for _ in range(r)])
temp = input()
q = deque()
escaped = False
for i in range(l):
for j in range(r):
for k in range(c):
if board[i][j][k] == 'S':
start = (i, j, k, 0)
visited[i][j][k] = True
if board[i][j][k] == 'E':
goal = (i, j, k)
q.append(start)
while q:
# print(f'cur q: {q}')
z, x, y, d = q.popleft()
if (z, x, y) == goal:
escaped = True
print(f'Escaped in {d} minute(s).')
break
nd = d + 1
for i in range(6):
nz = z + dz[i]
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nz < l and 0 <= nx < r and 0 <= ny < c and not visited[nz][nx][ny]:
if board[nz][nx][ny] == '.' or board[nz][nx][ny] == 'E':
q.append((nz, nx, ny, nd))
visited[nz][nx][ny] = True
if not escaped:
print('Trapped!')
📌 리뷰
- 3차원 접근이라 l,r,c 위치 확인 필요(첨에 이것때문에 꼬였음)
- break 설정하지 말기
728x90