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):# Write your code heren=len(grid)m=len(grid[0])directions=[(0,1),(1,0),(0,-1),(-1,0)]queue=deque([(startX,startY,0)])visited=set()visited.add((startX,startY))whilequeue:x,y,moves=queue.popleft()if(x,y)==(goalX,goalY):returnmovesfordx,dyindirections:nx,ny=x,ywhile0<=nx+dx<nand0<=ny+dy<mandgrid[nx+dx][ny+dy]!='X':nx+=dxny+=dyif(nx,ny)notinvisited:visited.add((nx,ny))queue.append((nx,ny,moves+1))return-1if__name__=='__main__':fptr=open(os.environ['OUTPUT_PATH'],'w')n=int(input().strip())grid=[]for_inrange(n):grid_item=input()grid.append(grid_item)first_multiple_input=input().rstrip().split()startX=int(first_multiple_input[0])startY=int(first_multiple_input[1])goalX=int(first_multiple_input[2])goalY=int(first_multiple_input[3])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 →
Solution in Python