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.
#!/bin/python3importmathimportosimportrandomimportreimportsys## Complete the 'minimumMoves' function below.## The function is expected to return an INTEGER.# The function accepts following parameters:# 1. STRING_ARRAY grid# 2. INTEGER startX# 3. INTEGER startY# 4. INTEGER goalX# 5. INTEGER goalY#fromcollectionsimportdequedefminimumMoves(grid,startX,startY,goalX,goalY):n=len(grid)m=len(grid[0])# Store visited cells to avoid cycles and redundant processingvisited=set()# Queue stores tuples of (x, y, moves)queue=deque([(startX,startY,0)])visited.add((startX,startY))whilequeue:x,y,moves=queue.popleft()ifx==goalXandy==goalY:returnmoves# Define the four cardinal directionsdirections=[(0,1),(0,-1),(1,0),(-1,0)]fordx,dyindirections:nx,ny=x,y# Slide as far as possible in the current directionwhileTrue:nx+=dxny+=dy# Check bounds and for obstaclesifnot(0<=nx<nand0<=ny<mandgrid[nx][ny]!='X'):break#Stopslidingifoutofboundsoranobstacleishit# Only add the final destination of the slide to the queueif(nx,ny)notinvisited:visited.add((nx,ny))queue.append((nx,ny,moves+1))# Goal is unreachablereturn-1if__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')n=int(input().strip())grid=[]for_inrange(n):grid.append(input())startX,startY,goalX,goalY=map(int,input().rstrip().split())result=minimumMoves(grid,startX,startY,goalX,goalY)fptr.write(str(result)+'\n')fptr.close()
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 →