Bot Saves Princess – HackerRank Problem Solution


Princess Peach is trapped in one of the four corners of a square grid. You are in the center of the grid and can move one step at a time in any of the four directions. Can you rescue the princess?

Input format

The first line contains an odd integer N (< 100) denoting the size of the grid. This is followed by an NxN grid. Each cell is denoted by ‘-‘ (ascii value: 45). The bot position is denoted by ‘m’ and the princess position is denoted by ‘p’.

The top left of the grid is indexed at (0,0) and the bottom right is indexed at (N-1,N-1)

Output Format:

Print out all the moves you take to rescue the princess in one go. Moves must be separated by ‘\n’ a newline. The valid outputs are LEFT or RIGHT or UP or DOWN.

Write a programme which takes two parameters – the integer N and the character array grid. The grid will be formatted exactly as you see it in the input, so for the sample input the princess is at grid[2][0]. The function shall output moves (LEFT, RIGHT, UP or DOWN) on consecutive lines to rescue/reach the princess. The goal is to reach the princess in as few moves as possible.





Here is original problem from HackerRank


Solution Logic

  • Find Bot position
  • Find the prince position
  • Find the row difference between bot and prince
  • Find the column difference between bot and prince
  • Iterate loop to move the bot from up and down
  • If prince row count is greater the bot then prints “Up” else print “Down”
  • Iterate loop to move the bot from right and left
  • If prince column count is greater the bot then prints “Right” else print “Left”.

Leave a Reply

Your email address will not be published. Required fields are marked *