[๋ฐฑ์ค] 5427๋ฒ. ๋ถ ๐ฅ๐ฅ ๋ฐ๋ก๊ฐ๊ธฐ
- ์๊ทผ์ด๊ฐ ๋จผ์ ์ด๋
- ๋ถ์ด ์ด๋
- ๊ฐ์ฅ์๋ฆฌ์ ์ค๋ฉด ํ์ถ
O(w * h)
O(t * w * h)
from collections import deque
import sys
input = sys.stdin.readline
def escape():
while q:
x, y, time = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# ์๊ทผ์ด
if building[x][y] == '@':
if 0 <= nx < h and 0 <= ny < w:
if building[nx][ny] == '.':
q.append((nx, ny, time + 1))
building[nx][ny] = '@'
else:
return time + 1
# ๋ถ
else:
if 0 <= nx < h and 0 <= ny < w and building[nx][ny] != '#' and building[nx][ny] != '*':
q.append((nx, ny, -1))
building[nx][ny] = '*'
return "IMPOSSIBLE"
t = int(input())
for _ in range(t):
w, h = map(int, input().split())
building = [list(input().strip()) for _ in range(h)]
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
q = deque([])
time = 0
# ์์น ์ฐพ๊ธฐ
for x in range(h):
for y in range(w):
# ์๊ทผ์ด
if building[x][y] == '@':
# ๋ฐ๋ก ํ์ถ ๊ฐ๋ฅํ๋ฉด ํ์ถํ๊ธฐ
if not( 0 < x < (h - 1) and 0 < y < (w - 1)):
time = 1
break
q.appendleft((x, y, 0))
# ๋ถ
elif building[x][y] == '*':
q.append((x, y, -1))
if time > 0:
break
# ํ์ถํ๊ธฐ
if time == 0:
time = escape()
print(time)
from collections import deque
import sys
input = sys.stdin.readline
def escape():
while q:
x, y, time = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# ์๊ทผ์ด
if building[x][y] == '@':
# ๊ฐ์ฅ์๋ฆฌ๋ผ์ ๋ฐ๋ก ํ์ถ ๊ฐ๋ฅํ ๋
if nx < 0 or ny < 0 or nx >= h or ny >= w:
return time + 1
# ๊ฐ์ฅ์๋ฆฌ๋ฅผ ์ ์ธํ ๋ฒ์์ผ ๋
elif 0 <= nx < h and 0 <= ny < w:
if building[nx][ny] == '.':
q.append((nx, ny, time + 1))
building[nx][ny] = '@'
# ๋ถ
else:
if 0 <= nx < h and 0 <= ny < w and building[nx][ny] != '#' and building[nx][ny] != '*':
q.append((nx, ny, -1))
building[nx][ny] = '*'
return "IMPOSSIBLE"
t = int(input())
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
for _ in range(t):
w, h = map(int, input().split())
building = [list(input().strip()) for _ in range(h)]
q = deque([])
# ์์น ์ฐพ๊ธฐ
for x in range(h):
for y in range(w):
# ์๊ทผ์ด
if building[x][y] == '@':
q.appendleft((x, y, 0))
# ๋ถ
elif building[x][y] == '*':
q.append((x, y, -1))
# ํ์ถํ๊ธฐ
print(escape())