We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
This is perfect python code using dijkstra algorithm.
importheapqdefmatrix_to_weighted_graph(matrix):rows,cols=len(matrix),len(matrix[0])graph={}foriinrange(rows):forjinrange(cols):node=(i,j)#Eachelementisanodeneighbors={}# Check and add valid neighbors with weights (value of neighboring element)ifi>0:#Upneighbors[(i-1,j)]=matrix[i-1][j]ifi<rows-1:#Downneighbors[(i+1,j)]=matrix[i+1][j]ifj>0:#Leftneighbors[(i,j-1)]=matrix[i][j-1]ifj<cols-1:#Rightneighbors[(i,j+1)]=matrix[i][j+1]graph[node]=neighborsgraph[(cols-1,rows-1)]={}returngraphdefdijkstra(graph,source,target):# Initialize distances and priority queuedistances={vertex:float('infinity')forvertexingraph}distances[source]=0priority_queue=[(0,source)]#(distance,vertex)whilepriority_queue:current_distance,current_vertex=heapq.heappop(priority_queue)# Skip if the distance is outdatedifcurrent_distance>distances[current_vertex]:continueforneighbor,weightingraph[current_vertex].items():distance=current_distance+weight# If a shorter path is foundifdistance<distances[neighbor]:distances[neighbor]=distanceheapq.heappush(priority_queue,(distance,neighbor))returndistances[target]T=int(input())matrix=[]foriinrange(T):line=list(map(int,input().split()))matrix.append(line)rows,cols=len(matrix),len(matrix[0])graph=matrix_to_weighted_graph(matrix)length=matrix[0][0]+dijkstra(graph,(0,0),(rows-1,cols-1))print(length)
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Project Euler #83: Path sum: four ways
You are viewing a single comment's thread. Return to all comments →
This is perfect python code using dijkstra algorithm.