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.
#First, build the neighborhood of nodes: for a given position, move in all directions and add possible nodes to the adjacency list# Then, do a BFS from start node, until we reach end node, count how many levels of BFS traversal needed fromcollectionsimportdefaultdict,dequedefcheck_go(i,j,d_i,d_j,grid,ngbs_ij):n=len(grid)cur_i=i+d_icur_j=j+d_jwhile0<=cur_i<nand0<=cur_j<nandgrid[cur_i][cur_j]=='.':ngbs_ij.append((cur_i,cur_j))cur_i+=d_icur_j+=d_jdefbuild_ngbs(grid):ngbs=defaultdict(list)n=len(grid)foriinrange(n):forjinrange(n):ifgrid[i][j]=='.':#check ngbscheck_go(i,j,0,-1,grid,ngbs[(i,j)])check_go(i,j,0,+1,grid,ngbs[(i,j)])check_go(i,j,-1,0,grid,ngbs[(i,j)])check_go(i,j,+1,0,grid,ngbs[(i,j)])returnngbsdefminimumMoves(grid,startX,startY,goalX,goalY):ngbs=build_ngbs(grid)q=deque()visited=set()q.append((startX,startY))visited.add((startX,startY))level_counter=-1whileq:level_size=len(q)level_counter+=1for_inrange(level_size):node=q.popleft()ifnode==(goalX,goalY):returnlevel_counterforneighborinngbs[node]:ifneighbornotinvisited:visited.add(neighbor)q.append(neighbor)
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 →