https://www.acmicpc.net/problem/2665
다익스트라 활용
- 벽을 부순 횟수를 기준으로 우선순위 큐를 이용
- 벽을 부순 횟수가 가장 적은 순서부터 이동
- 종점에 도달시 현재 상태의 벽을 부순 횟수 return
import heapq,sys
input = sys.stdin.readline
def solution(n):
arr = [input() for _ in range(n)]
dr,dc = (1,0,-1,0),(0,1,0,-1)
h = [(0,0,0)]
check = [[2500]*n for _ in range(n)]
N = n-1
while h:
cnt,r,c = heapq.heappop(h)
if check[r][c] < cnt:
continue
for way in range(4):
nr,nc = r+dr[way], c+dc[way]
if 0<=nr<n and 0<=nc<n:
if nr == N and nc == N:
return cnt
if check[nr][nc] <= cnt:
continue
elif arr[nr][nc] == '1':
heapq.heappush(h,(cnt,nr,nc))
check[nr][nc] = cnt
else:
heapq.heappush(h,(cnt+1,nr,nc))
check[nr][nc] = cnt+1
n = int(input())
ans = solution(n)
print(ans)
'알고리즘 문제 풀이 > Python' 카테고리의 다른 글
python 백준 25214 크림 파스타 (0) | 2023.02.27 |
---|---|
python 백준 1103 게임 (0) | 2023.02.10 |
python 백준 27210 신을 모시는 사당 (0) | 2023.01.25 |
python 백준 10164 격자상의 경로 (1) | 2023.01.25 |
python 백준 2623 음악프로그램 (0) | 2023.01.11 |