๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿƒ algorithm/boj

BOJ 6593 - ์ƒ๋ฒ” ๋นŒ๋”ฉ

by HandHand 2021. 3. 18.

๋ฌธ์ œ

๋ฐฑ์ค€ ์˜จ๋ผ์ธ ์ €์ง€ - 6593๋ฒˆ

ํ’€์ด ๊ณผ์ •

์‹œ์ž‘ ์ง€์ ์—์„œ ๋ชฉํ‘œ ์ง€์ ์— ๋„๋‹ฌํ•˜๊ธฐ ์œ„ํ•œ ์ตœ๋‹จ ๊ฑฐ๋ฆฌ๋ฅผ ๊ตฌํ•˜๋Š” BFS ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.
๋นŒ๋”ฉ์ด 3์ฐจ์›์ด๊ธฐ ๋•Œ๋ฌธ์— ์ƒํƒœ๊ณต๊ฐ„์„ ๋‹ค์Œ๊ณผ ๊ฐ™์ด ์ •์˜ํ•ด์ค๋‹ˆ๋‹ค.


visit[z][x][y] = z ์ธต์˜ (x, y) ์ง€์ ์— ๋ฐฉ๋ฌธํ–ˆ๋Š”์ง€ ์œ ๋ฌด๋ฅผ ์ €์žฅ


์—ฌ๊ธฐ์„œ z ์ถ• ์„ ์ฒซ๋ฒˆ์งธ ์ธ๋ฑ์Šค๋กœ ์ง€์ •ํ•œ ๊ฒƒ์€ ๊ตฌํ˜„์ƒ์˜ ํŽธ์˜๋ฅผ ์œ„ํ•œ ๊ฒƒ์ž…๋‹ˆ๋‹ค.
๊ฐ ์ง€์ ๋“ค์„ ๋ฐฉ๋ฌธํ•  ๋•Œ ๋™์„œ๋‚จ๋ถ ๋ฐ ์œ„์ธต, ์•„๋ž˜์ธต ๊นŒ์ง€ ๊ฐ™์ด ํƒ์ƒ‰์„ ์ˆ˜ํ–‰ํ•˜๋ฉฐ ๋„๋‹ฌ ์—ฌ๋ถ€๋ฅผ ํŒ๋‹จํ•ด์ฃผ๋ฉด ๋ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
from collections import deque

L, R, C = 0, 0, 0
building = []


dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
dz = [1, -1]


def bfs(start):
    q = deque()
    visit = [[[0] * C for _ in range(R)] for _ in range(L)]

    q.append([start[0], start[1], start[2], 0])
    visit[start[0]][start[1]][start[2]] = 1

    while q:
        z, x, y, cost = q.popleft()

        if building[z][x][y] == 'E':
            return cost

        # ๋™์„œ๋‚จ๋ถ ์ด๋™
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]
            if 0 <= nx < R and 0 <= ny < C:
                if not visit[z][nx][ny] and building[z][nx][ny] != '#':
                    visit[z][nx][ny] = 1
                    q.append([z, nx, ny, cost + 1])

        # ์ƒํ•˜ ์ด๋™
        for i in range(2):
            nz = z + dz[i]
            if 0 <= nz < L:
                if not visit[nz][x][y] and building[nz][x][y] != '#':
                    visit[nz][x][y] = 1
                    q.append([nz, x, y, cost + 1])

    return -1


def solution():
    start = []

    # ์‹œ์ž‘์ง€์  ์ฐพ๊ธฐ
    for z in range(L):
        for x in range(R):
            for y in range(C):
                if building[z][x][y] == 'S':
                    start = [z, x, y]

    return bfs(start)


if __name__ == '__main__':
    while True:
        L, R, C = list(map(int, sys.stdin.readline().split()))
        if not L and not R and not C:
            break

        building = []
        for _ in range(L):
            building.append([list(sys.stdin.readline().strip()) for _ in range(R)])
            sys.stdin.readline()

        ans = solution()
        if ans != -1:
            print(f'Escaped in {ans} minute(s).')
        else:
            print('Trapped!')
๋ฐ˜์‘ํ˜•

'๐Ÿƒ algorithm > boj' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ 15732 - ๋„ํ† ๋ฆฌ ์ˆจ๊ธฐ๊ธฐ  (0) 2021.03.18
BOJ 2178 - ๋ฏธ๋กœ ํƒ์ƒ‰  (0) 2021.03.18
BOJ 16397 - ํƒˆ์ถœ  (0) 2021.03.18
BOJ 2563 - ์ƒ‰์ข…์ด  (0) 2021.03.18
BOJ 1963 - ์†Œ์ˆ˜ ๊ฒฝ๋กœ  (0) 2021.03.18

๐Ÿ’ฌ ๋Œ“๊ธ€