Castle on the grid HackerRank solution

published on 28 May 2024

The "Castle on the Grid" problem on HackerRank involves navigating a grid filled with open and blocked cells, akin to a chessboard where a rook moves along rows or columns. The challenge is to determine the minimum number of moves required to get from a start position to a goal position on the grid. You can only move in straight lines until you hit an obstacle or the edge of the grid.

The problem requires implementing an algorithm that efficiently explores possible paths, and it's typically solved using a breadth-first search (BFS).

In this post, we will demonstrate how our tool, HackerRankGPT, can give you the Castle on the grid HackerRank solution, and help you succeed in your HackerRank coding interview.

HackerRankGPT, powered by GPT-4, provides real-time, undetectable support for solving coding problems during your HackerRank interviews 👈

Here is the Castle on the grid HackerRank problem and solution using HackerRankGPT:

Castle on the grid hackerrank problem statement
Castle on the grid hackerrank problem statement

Castle on the grid hackerrank solution:

#!/bin/python3

import math
import os
import random
import re
import sys
from collections import deque

#
# 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
#

def minimumMoves(grid, startX, startY, goalX, goalY):
    n = len(grid)
    queue = deque([(startX, startY, 0)])  # queue of (x, y, distance)
    visited = set([(startX, startY)])
    
    while queue:
        x, y, dist = queue.popleft()
        
        if (x, y) == (goalX, goalY):
            return dist
        
        # Directions for movement: right, left, down, up
        directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        
        for dx, dy in directions:
            nx, ny = x + dx, y + dy
            
            while 0 <= nx < n and 0 <= ny < n and grid[nx][ny] == '.':
                if (nx, ny) not in visited:
                    visited.add((nx, ny))
                    queue.append((nx, ny, dist + 1))
                nx += dx
                ny += dy

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)

    fptr.write(str(result) + '\n')

    fptr.close()

Explanation

  1. Initialization: We set up the BFS with a queue that includes the start position, and a set to track visited positions.
  2. BFS Loop: We extract the current position and check if it is the goal. If so, return the distance. Otherwise, for each movement direction, move as far as possible until hitting an obstacle or the boundary, adding each new position to the queue if not visited.
  3. Handling Input/Output: Standard code to handle input and output based on the problem constraints.

When we use this code, we pass all HackerRank tests:

Castle on the grid solved using HackerRankGPT
Castle on the grid solved using HackerRankGPT

If you have a HackerRank coding test soon, you can use HackerRankGPT to your advantage. It will undetectably assist you during your interview and help ensure you get the job.

AI is here now, and other candidates might be using it to get ahead and win the job.

Use HackerRankGPT. 
Don't fall behind.

Read more

Built on Unicorn Platform