전북대학교 리트머스 과제 ( 이경수 교수님 알고리즘 과제)


4 4
6 7 12 5
5 3 11 18
7 17 3 3
8 10 14 9
40
해당 문제를 처음 봤을 때 딱 떠 오른 문제가 있다. 바로 이전에 bfs로 시작 점부터 끝점까지 탐색을 했었던 문제 ‘쩰리’ 문제였다.
하지만 이전의 쩰리 문제와 다른점은 ‘잡스가 학교에 빠르게 가기 위해서는 걸리는 시간의 합이 최소가 되어야 한다’라는 부분이 추가가 되었다는 것이었다.
from collections import deque
import sys
input = sys.stdin.readline
n,m = map(int,input().rstrip().rsplit())
INF = 1e9
#가장 왼쪽 좌표 1,1
#우리는 0,0 ~ 3,3으로 간다
road = []
dp = [[INF] * m for _ in range(n)]
#그래프 생성
for _ in range(n):
road.append(list(map(int,input().rstrip().rsplit())))
dp[0][0] = road[n-1][m-1]
def bfs(graph,dp,n,m):
#출발 0,0
q = deque()
q.append((0,0))
dx = [0,1]
dy = [1,0]
while q:
cur_y,cur_x = q.popleft()
#아래, 오른쪽 이동
for i in range(2):
next_y = dy[i] + cur_y
next_x = dx[i] + cur_x
#범위 확인
if 0 <= next_y < n and 0 <= next_x < m:
new_time = dp[cur_y][cur_x] + graph[cur_y][cur_x]
if new_time < dp[next_y][next_x]:
dp[next_y][next_x] = new_time
q.append((next_y,next_x))
return dp
result = bfs(road,dp,n,m)
print(result[n-1][m-1])
방문처리의 유무
dp 배열의 의미 정의