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

BOJ 9311 - Robot in a Maze

by HandHand 2021. 3. 14.

๋ฌธ์ œ

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

ํ’€์ด ๊ณผ์ •

์‹œ์ž‘ ์ง€์ ์—์„œ ๋ชฉํ‘œ ์ง€์ ์— ๋„๋‹ฌํ•˜๊ธฐ ์œ„ํ•œ ์ตœ๋‹จ ์ด๋™ ํšŸ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ์ „ํ˜•์ ์ธ BFS ๋ฌธ์ œ์ž…๋‹ˆ๋‹ค.

๋ณด๋“œ๋ฅผ ์ž…๋ ฅ๋ฐ›์€ ๋‹ค์Œ ์‹œ์ž‘ ์ง€์ ์„ ๋จผ์ € ์ฐพ์€ ๋‹ค์Œ, BFS ๋ฅผ ํ†ตํ•ด์„œ ๋ชฉํ‘œ ์ง€์  G ๋ฅผ ์ฐพ์„ ๋•Œ๊นŒ์ง€ ์ˆœํšŒํ•ฉ๋‹ˆ๋‹ค.

์ฝ”๋“œ


import sys
from collections import deque


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


def pre_processing(board, R, C):
    for x in range(R):
        for y in range(C):
            if board[x][y] == 'S':
                return [x, y]


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

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

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

        if board[x][y] == 'G':
            return cost

        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]

            if 0 <= nx < R and 0 <= ny < C:
                if board[nx][ny] in ['O', '0', 'G'] and not visit[nx][ny]:
                    visit[nx][ny] = 1
                    q.append([nx, ny, cost + 1])

    return 0


def solution(board, R, C):
    start = pre_processing(board, R, C)
    cost = bfs(start, board, R, C)

    return cost


if __name__ == '__main__':
    T = int(input())

    for _ in range(T):
        R, C = list(map(int, sys.stdin.readline().split()))
        board = [list(sys.stdin.readline().strip()) for _ in range(R)]

        answer = solution(board, R, C)

        if answer:
            print(f"Shortest Path: {answer}")
        else:
            print("No Exit")
๋ฐ˜์‘ํ˜•

๐Ÿ’ฌ ๋Œ“๊ธ€