1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| from sys import stdin import heapq
n = int(stdin.readline()) for i in range(n): N = int(stdin.readline()) M = int(stdin.readline()) mapp = [] for k in range(N): mapp.append(list(map(int, stdin.readline().split()))) #pq = [[0, 0, 0]] #雖然用一般arr 但之後取min? pq = [] heapq.heappush(pq, [mapp[0][0], 0, 0]) used = [[0 for i in range(M)]for i in range(N)] #red ans = [[999 for i in range(M)]for i in range(N)] ans[0][0] = mapp[0][0] while pq: cost, x, y = heapq.heappop(pq) #used[x][y] = 1 if used[x][y] == 1: continue used[x][y] = 1 if x == N - 1 and y == M - 1: print(ans[x][y]) break if x + 1 < N and used[x+1][y] == 0: if cost + mapp[x+1][y] < ans[x+1][y] and used[x+1][y] == 0: heapq.heappush(pq, [cost+mapp[x+1][y], x+1, y]) ans[x+1][y] = cost + mapp[x+1][y] if x - 1 >= 0 and used[x-1][y] == 0 : if cost + mapp[x-1][y] < ans[x-1][y] and used[x-1][y] == 0: heapq.heappush(pq, [cost+mapp[x-1][y], x-1, y]) ans[x-1][y] = cost + mapp[x-1][y] if y + 1 < M and used[x][y+1] == 0 : if cost + mapp[x][y+1] < ans[x][y+1] and used[x][y+1] == 0: heapq.heappush(pq, [cost+mapp[x][y+1], x, y+1]) ans[x][y+1] = cost + mapp[x][y+1] if y - 1 >= 0 and used[x][y-1] == 0: if cost + mapp[x][y-1] < ans[x][y-1] and used[x][y-1] == 0: heapq.heappush(pq, [cost+mapp[x][y-1], x, y-1]) ans[x][y-1] = cost + mapp[x][y-1]
|