๐Ÿ—๏ธ Algorithm/๐ŸŸฉ ๋ฐฑ์ค€

๐ŸŸฉ [๋ฐฑ์ค€] [Python] [Gold4] 4179๋ฒˆ_๋ถˆ!

Dbswnstjd 2023. 4. 11. 15:10

๋ฌธ์ œ

https://www.acmicpc.net/problem/4179

 

4179๋ฒˆ: ๋ถˆ!

์ž…๋ ฅ์˜ ์ฒซ์งธ ์ค„์—๋Š” ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„๋œ ๋‘ ์ •์ˆ˜ R๊ณผ C๊ฐ€ ์ฃผ์–ด์ง„๋‹ค. ๋‹จ, 1 ≤ R, C ≤ 1000 ์ด๋‹ค. R์€ ๋ฏธ๋กœ ํ–‰์˜ ๊ฐœ์ˆ˜, C๋Š” ์—ด์˜ ๊ฐœ์ˆ˜์ด๋‹ค. ๋‹ค์Œ ์ž…๋ ฅ์œผ๋กœ R์ค„๋™์•ˆ ๊ฐ๊ฐ์˜ ๋ฏธ๋กœ ํ–‰์ด ์ฃผ์–ด์ง„๋‹ค. ๊ฐ๊ฐ์˜ ๋ฌธ์ž

www.acmicpc.net

ํ’€์ด

# ๋ฐฑ์ค€ 4179๋ฒˆ ๋ฌธ์ œ - ๋ถˆ!
import sys
from collections import deque
input = sys.stdin.readline

n, m = map(int, input().split())
graph = []

for i in range(n):
    graph.append(list(input().rstrip()))
    if 'J' in graph[i]:
        q = deque([(0, i, graph[i].index('J'))])

for i in range(n):
    for j in range(m):
        if graph[i][j] == 'F':
            q.append((-1, i, j))

dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
ans = 'IMPOSSIBLE'

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

    # ์ง€ํ›ˆ์ด ํƒˆ์ถœ
    if time > -1 and graph[x][y] != 'F' and (x == 0 or y == 0 or x == n - 1 or y == m - 1):
        ans = time + 1
        break

    for i in range(4):
        nx = x + dx[i]
        ny = y + dy[i]
        if 0 <= nx < n and 0 <= ny < m and graph[nx][ny] != '#':

            # ์ง€ํ›ˆ์ด ์ด๋™
            if time > -1 and graph[nx][ny] == '.':
                graph[nx][ny] = '_'
                q.append((time + 1, nx, ny))

            # ๋ถˆ ํผ๋œจ๋ฆฌ๊ธฐ
            elif time == -1 and graph[nx][ny] != 'F':
                graph[nx][ny] = 'F'
                q.append((-1, nx, ny))

print(ans)

๋ฌธ์ œ๋ฅผ ํ’€๋‹ค๊ฐ€ ๋„์ €ํžˆ ์ดํ•ด๊ฐ€ ์•ˆ๋˜์„œ ๊ตฌ๊ธ€๋ง์„ ํ–ˆ๋‹ค.