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.
def minimumMoves(grid, startX, startY, goalX, goalY):
# Define the directions for up, down, left, right movements
directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
# Create a queue for BFS and enqueue the starting position with 0 moves
queue = deque([(startX, startY, 0)])
# Create a set to keep track of visited positions
visited = set()
visited.add((startX, startY))
# Get the size of the grid
n = len(grid)
# Perform BFS
while queue:
x, y, moves = queue.popleft()
# Check if we have reached the goal
if (x, y) == (goalX, goalY):
return moves
# Try all 4 possible directions
for dx, dy in directions:
nx, ny = x, y
# Move in the current direction until hitting a wall or boundary
while 0 <= nx + dx < n and 0 <= ny + dy < n and grid[nx + dx][ny + dy] == '.':
nx += dx
ny += dy
# If this new position has not been visited, add it to the queue
if (nx, ny) not in visited:
queue.append((nx, ny, moves + 1))
visited.add((nx, ny))
# If the goal is not reachable, return -1 (though in the problem it's guaranteed to be reachable)
return -1
if name == 'main':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input().strip())
grid = []
for _ in range(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)
deque helps in improving time complexity to O(1) ... while append and pop the points/elements.
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 →
Python easy implementation using deque:
import os from collections import deque
def minimumMoves(grid, startX, startY, goalX, goalY): # Define the directions for up, down, left, right movements directions = [(1, 0), (-1, 0), (0, 1), (0, -1)]
if name == 'main': fptr = open(os.environ['OUTPUT_PATH'], 'w')
deque helps in improving time complexity to O(1) ... while append and pop the points/elements.