import sys
from collections import deque
sys.stdin = open('input.txt', 'rt')
input = sys.stdin.readline
N, M = map(int, input().split())
graph = []
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
for _ in range(N):
graph.append(list(input().strip()))
visited = [[0] * M for _ in range(N)]
def bfs():
global start, water, end, queue
while queue:
while queue:
position_y, position_x = queue.popleft()
print(graph)
if position_y == end[0] and position_x == end[1]:
print(graph[end[0]][end[1]])
break
for i in range(4):
ny = position_y + dy[i]
nx = position_x + dx[i]
if 0 <= ny < 3 and 0 <= nx < 3 and graph[ny][nx] == '.':
graph[ny][nx] = graph[position_y][position_x] + 1
queue.append((ny, nx))
while water:
position_y, position_x = water.popleft()
for i in range(4):
ny = position_y + dy[i]
nx = position_x + dx[i]
if 0 <= ny < 3 and 0 <= nx < 3 and visited[ny][nx] == 0:
visited[ny][nx] = 1
water.append((ny, nx))
print('KAKTUS')
for y in range(N):
for x in range(M):
if graph[y][x] == 'S':
queue = deque()
queue.append((y, x))
graph[y][x] = 1
if graph[y][x] == '*':
water = deque()
water.append((y, x))
visited[y][x] = 1
if graph[y][x] == 'D':
end = [y, x]
bfs()
from collections import deque
R, C = map(int, input().split())
graph = [list(input()) for _ in range(R)]
visited = [[False] * C for _ in range(R)] # True, False로 좌표 체크
sonic = deque() # 고슴도치
water = deque() # 물
count = 0 # 시간(초) 카운트
# 방향 설정
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
# 물, 고슴도치 좌표 추가. 방문 True로 설정
for i in range(R):
for j in range(C):
if graph[i][j] == '*':
water.append((i, j))
visited[i][j] = True
elif graph[i][j] == 'S':
sonic.append((i, j))
visited[i][j] = True
elif graph[i][j] == 'X':
visited[i][j] = True
# 고슴도치 이동가능할때마다 반복문
while sonic:
# 물 현황
for i in range(len(water)):
w_x, w_y = water.popleft()
for j in range(4):
nx = w_x + dx[j]
ny = w_y + dy[j]
if 0 <= nx < R and 0 <= ny < C:
if graph[nx][ny] == '.':
water.append((nx, ny))
graph[nx][ny] = '*'
visited[nx][ny] = True
# 물 확장시 시간 추가. 고슴도치는 물이 찰 예정 칸으로 이동할 수 없기 때문에 고슴도치 구현보다 먼저 카운트
count += 1
# 고슴도치 움직이는 로직 구현
for _ in range(len(sonic)):
s_x, s_y = sonic.popleft()
for i in range(4):
nx = s_x + dx[i]
ny = s_y + dy[i]
if 0 <= nx < R and 0 <= ny < C:
if graph[nx][ny] =='.' and visited[nx][ny] == False:
sonic.append((nx, ny))
visited[nx][ny] = True
elif graph[nx][ny] == 'D':
print(count)
exit()
print('KAKTUS')
for 문을 2번 사용해서 해결하는 코드이다. 5427번 불 문제랑 비슷한 것 같다.
백준 5427번 불 문제 처럼 while을 2개 써서 구하려 했는데 어제는 이해 했다고 생각해서 구해봤는데 아직 덜 이해가 된 것 같다. 하지만 이번에 탈출의 정답 코드는 for문을 2개 사용해서 구했는데 이게 좀 더 나에게 쉽게 와 닿는 것 같다.