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.
i solved by building a graph of points on the grid and calculating distance using dijkstra's algo
fromcollectionsimportdefaultdictimportheapqdefdijkstra(graph,start):distances={node:float("inf")fornodeingraph}distances[start]=0previous_nodes={node:Nonefornodeingraph}priority_queue=[(0,start)]whilepriority_queue:current_distance,current_node=heapq.heappop(priority_queue)ifcurrent_distance>distances[current_node]:continueforneighbor,weightingraph[current_node].items():distance=current_distance+weightifdistance<distances[neighbor]:distances[neighbor]=distanceprevious_nodes[neighbor]=current_nodeheapq.heappush(priority_queue,(distance,neighbor))returndistances,previous_nodesdefminimumMoves(grid,startX,startY,goalX,goalY):# Write your code herenodes=defaultdict(dict)length=len(grid[0])# create graph of nodes and edgesfory,rowinenumerate(grid):forx,columninenumerate(row):ifgrid[y][x]=="X":continue# move up and add edgesi,j=x-1,y# go leftwhilei>=0andgrid[j][i]!="X":nodes[(x,y)][(i,j)]=1i-=1# go righti,j=x+1,ywhilei<lengthandgrid[j][i]!="X":nodes[(x,y)][(i,j)]=1i+=1i,j=x,y-1# go downwhilej>=0andgrid[j][i]!="X":nodes[(x,y)][(i,j)]=1j-=1# go upi,j=x,y+1whilej<lengthandgrid[j][i]!="X":nodes[(x,y)][(i,j)]=1j+=1maps=dijkstra(nodes,(startY,startX))returnmaps[0][(goalY,goalX)]
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Castle on the Grid
You are viewing a single comment's thread. Return to all comments →
i solved by building a graph of points on the grid and calculating distance using dijkstra's algo