skip to Main Content

I’m doing an Artificial Intelligence track at HackerRank and this is the first time I do this kind of programs.

On the first program, https://www.hackerrank.com/challenges/saveprincess/problem, I have to do the following:

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 (3 <= 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’.

Grid is indexed using Matrix Convention

Output format

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

What should I do in these kind of problems?

Move to one corner and check if the princess is there, and it is not, move to another corner?

Here the goal is to do it in as few steps as possible but I think that will only happen if I’m lucky and I find the princess in the first corner to which I move.

I have thought that I could check if the princess is the corner I’m moving to before move to it, but I don’t know if it is allowed in this problem.

2

Answers


  1. Read the description of the input format (emphasis mine):

    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’.

    You do not have to actually go to each corner to see whether the princess is there, you already know where she is! Just determine the difference in position of the cells containing the bot m and the princess p and print the accordant movements. E.g., if the difference is 2 in x and -1 and y direction, you might go right right up.

    Login or Signup to reply.
  2. What a boring problem… Seriously.

    1. Load in the input data, starting with the grid size.
    2. Accept lines of input corresponding to the grid size.
    3. Since you know that the grid is a square, check the corners and move diagonally corresponding to what corner the princess is in.

    Solution in 7 lines of python:

    gridsize  = int(input('Enter number of rows: '))
    grid      = [ input('Enter row: ') for r in range(gridsize) ]
    move_dist = (gridsize-1)//2
    if   grid[ 0][ 0] == 'p': print('n'.join([   'UPnLEFT'] * move_dist))
    elif grid[ 0][-1] == 'p': print('n'.join([  'UPnRIGHT'] * move_dist))
    elif grid[-1][ 0] == 'p': print('n'.join([ 'DOWNnLEFT'] * move_dist))
    elif grid[-1][-1] == 'p': print('n'.join(['DOWNnRIGHT'] * move_dist))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search