728x90
반응형
https://www.acmicpc.net/problem/3055
3055번: 탈출
사악한 암흑의 군주 이민혁은 드디어 마법 구슬을 손에 넣었고, 그 능력을 실험해보기 위해 근처의 티떱숲에 홍수를 일으키려고 한다. 이 숲에는 고슴도치가 한 마리 살고 있다. 고슴도치는 제
www.acmicpc.net
<풀이>
한 그래프는 물의 이동을 그리는 그래프, 한 그래프는 거리를 담아두는 그래프를 그린다.
<전체 코드>
import sys
from collections import deque
R, C = map(int, sys.stdin.readline().split())
graph = []
disGraph = [[float('inf') for _ in range(C)] for _ in range(R)]
waters = []
for i in range(R):
temp = list(map(str, sys.stdin.readline().rstrip()))
for j in range(C):
if temp[j] == 'S':
S_row, S_col = i, j
if temp[j] == 'D':
D_row, D_col = i, j
if temp[j] == '*':
waters.append([i, j])
graph.append(temp)
disGraph[S_row][S_col] = 0
cnt = 0
drow = [-1, 0, 1, 0]
dcol = [0, 1, 0, -1]
answer = float('inf')
queue = deque([[S_row, S_col, waters, graph]])
while queue:
nowRow, nowCol, nowWaters, temp = queue.pop()
nowGraph = [i[:] for i in temp]
nowCnt = disGraph[nowRow][nowCol]
new_waters = []
while nowWaters:
wr, wc = nowWaters.pop()
for i in range(4):
nextWr = wr+drow[i]
nextWc = wc+dcol[i]
if not 0 <= nextWr < R:
continue
if not 0 <= nextWc < C:
continue
if nowGraph[nextWr][nextWc] not in ['D', '*', 'X']:
nowGraph[nextWr][nextWc] = '*'
new_waters.append([nextWr, nextWc])
nowCnt += 1
for i in range(4):
nextRow = nowRow+drow[i]
nextCol = nowCol+dcol[i]
if not 0 <= nextRow < R:
continue
if not 0 <= nextCol < C:
continue
next = nowGraph[nextRow][nextCol]
if next in ['*', 'X']:
continue
elif next == 'D':
if nowCnt < answer:
answer = nowCnt
elif nowCnt < disGraph[nextRow][nextCol]:
disGraph[nextRow][nextCol] = nowCnt
queue.appendleft([nextRow, nextCol, new_waters[:], nowGraph])
print(answer if answer != float('inf') else 'KAKTUS')
728x90
반응형
'# Coding > # 백준' 카테고리의 다른 글
[백준 / 7569] 토마토 - Python (0) | 2022.03.03 |
---|---|
[백준 / 17298] 오큰수 - Python (0) | 2022.02.22 |
[백준 / 1922] 네트워크 연결 - Python (0) | 2022.02.16 |
[백준 / 1043] 거짓말 - Python (0) | 2022.02.10 |
[백준 / 1022] 소용돌이 예쁘게 출력하기 - Python (0) | 2022.02.09 |