[백준] 6593 상범 빌딩 (골드 5)

2023. 3. 21. 00:30ps

bfs를 활용하여 두 지점이 연결되어 있는 지 여부를 판단하는 전형적인 문제이다.

 

삼차원 배열을 받아오는 과정에서 어색한 느낌이 있었다.

 

그리고 다음 위치를 판단하는 과정에서 갈 수 있는 곳을 기준으로 체크하다보니 'E' 지점을 포함시키지 못해서 에러가 계속 났다.

갈 수 없는 곳을 기준으로 체크해서 해결할 수 있었다.

 

이동거리를 방문처리배열의 값으로 지정해주는 방식으로 큐에 넣는 원소의 개수를 최소화했다. (큐에 넣는 것도 가능하다.)

 

from collections import deque
import sys
input = sys.stdin.readline


## L : 층
## R : 행
## C : 열

while True:
    L, R, C = map(int, input().rstrip().split())

    if L == R == C == 0:
        break

    building = []

    for i in range(L):
        ithFloor = []
        for j in range(R):

            nowColumn = list(input().rstrip())

            for k in range(C):
                
                ## 시작점을 저장
                if nowColumn[k] == 'S':
                    startL, startR, startC = i, j, k

                ## 끝점을 저장
                elif nowColumn[k] == 'E':
                    endL, endR, endC = i, j, k

            ithFloor.append(nowColumn)
                    

        building.append(ithFloor)
        newLine = list(input().rstrip())


    
    queue = deque()
    visited = [[[-1 for _ in range(C)] for _ in range(R)] for _ in range(L)]

    queue.append((startL, startR, startC))
    visited[startL][startR][startC] = 0

    dL = [0,0,0,0,1,-1]
    dR = [0,0,1,-1,0,0]
    dC = [1,-1,0,0,0,0]

    possible = False

    while queue:
        nowL, nowR, nowC = queue.popleft()

        if (nowL, nowR, nowC) == (endL, endR, endC):
            possible = True
            count = visited[nowL][nowR][nowC]
            break


        for i in range(6):
            nextL = nowL + dL[i]
            nextR = nowR + dR[i]
            nextC = nowC + dC[i]

            
            ## 빌딩을 벗어나면 continue
            if not (0 <= nextL < L and 0 <= nextR < R and 0 <= nextC < C):
                continue

            if visited[nextL][nextR][nextC] == -1 and building[nextL][nextR][nextC] != '#':
                visited[nextL][nextR][nextC] = visited[nowL][nowR][nowC] + 1
                queue.append((nextL, nextR, nextC))
        


    if possible:
        print(f"Escaped in {count} minute(s).")

    else:
        print("Trapped!")

 

'ps' 카테고리의 다른 글

[백준] 2226 이진수 (골드 4)  (0) 2023.05.14
[백준] 20187 종이접기 (골드 3)  (0) 2023.05.13
[백준] 2240 자두나무 (골드 5)  (0) 2023.03.27
[백준] 2251 물통 (골드 5)  (0) 2023.03.22
[백준] 1039 교환 (골드 3)  (0) 2023.03.02