문제링크
https://www.acmicpc.net/problem/1261
코드
import sys
import heapq
input = sys.stdin.readline
def dijkstra(x,y):
q = []
distance[x][y] = 0
heapq.heappush(q,(0,x,y))
while q:
dist,x,y = heapq.heappop(q)
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if nx<0 or ny<0 or nx>=n or ny>=m:continue
cost = dist + graph[nx][ny]
if cost<distance[nx][ny]:
distance[nx][ny] = cost
heapq.heappush(q,(distance[nx][ny], nx,ny))
return distance[-1][-1]
m,n = map(int,input().split())
INF = float('inf')
graph = [list(map(int,input().strip())) for _ in range(n)]
distance = [[INF]*(m) for _ in range(n)]
dx,dy = [-1,1,0,0], [0,0,-1,1]
print(dijkstra(0, 0))
문제풀이
기본적인 다익스트라 유형과 아주 유사하다. 기본적인 다익스트라 유형은 한 노드에서 갈 수 있는 노드들을 확인해보는 반면 이 문제는 상,하,좌,우를 확인한다. 그런 의미에서 graph[nx][ny]는 graph[x][y]에서 갈 수 있는 가중치가 된다. 따라서 graph[nx][ny]+dist가 distance[ny][ny]보다 작다면 ( 더 빨리 갈 수 있다면) 값을 갱신해주면 된다.
또한 bfs로도 풀 수 있는데 4방향을 검사하고 아직 방문하지 않았고 0(벽이 아니면) q의 앞에, 1(벽이면) q의 뒤에 append해주면 부셔야하는 최소한의 벽의 갯수를 구할 수 있다. 위 코드에서 다익스트라가 최소힙으로 동작하기 때문에 이와 같은 개념으로 볼 수 있다.
'Koala - 10기 > 코딩테스트 준비 스터디' 카테고리의 다른 글
[백준/Python] 23033 : 집에 빨리 가고 싶어! (0) | 2023.05.20 |
---|---|
[백준/Python] 14497 주난의 난 (0) | 2023.05.20 |
[백준/C++] 2644 : 촌수계산 (0) | 2023.05.18 |
[백준/Python] 2606번: 바이러스 (0) | 2023.05.15 |
[백준/Python] #14502 연구소 (0) | 2023.05.14 |