๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 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")
๋ฐ์ํ
'๐ algorithm > boj' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ 15723 - n๋จ ๋ ผ๋ฒ (0) | 2021.03.18 |
---|---|
BOJ 14496 - ๊ทธ๋, ๊ทธ๋จธ๊ฐ ๋์ด (0) | 2021.03.16 |
BOJ 20005 - ๋ณด์ค๋ชฌ์คํฐ ์ ๋ฆฌํ (0) | 2021.03.14 |
BOJ 17521 - Byte Coin (0) | 2021.03.14 |
BOJ 20363 - ๋น๊ทผ ํค์ฐ๊ธฐ (0) | 2021.03.14 |
๐ฌ ๋๊ธ