Hackerrank - Artificial Intelligence - Bot Building

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.

Sample input
3
---
-m-
p--

Sample output
DOWN
LEFT

Task

Complete the function displayPathtoPrincess which takes in 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.

The above sample input is just to help you understand the format. The princess ('p') can be in any one of the four corners.

# Enter your code here. Read input from STDIN. Print output to STDOUT
#!/bin/python
def displayPathtoPrincess(n,ip):
    for col,k in enumerate(ip):
        if 'm' or 'p' in k:
            for ind, d in enumerate (k):
                if d == 'm':
                    indm = [col,ind]
                elif d == 'p':
                    indp = [col,ind]
    UP = DOWN = RIGHT = LEFT = 0
    if indm[0] >= indp[0]:
        UP = indm[0]-indp[0]
    elif indm[0] = indp[1]:
        LEFT = indm[1]-indp[1]
    elif indm[0] < indp[1]:
        RIGHT = indp[1] - indm[1]
 
    while UP or DOWN:
        if UP:
            print 'UP'
            UP -=1
        else:
            print 'DOWN'
            DOWN -= 1
    while LEFT or RIGHT:
        if LEFT:
            print 'LEFT'
            LEFT -= 1
        else:
            print 'RIGHT'
            RIGHT -= 1

#print all the moves here
m = input()

grid = []
for i in xrange(0, m):
    grid.append(list(raw_input().strip()))


displayPathtoPrincess(m,grid)

Comments

  1. I have read many article here and learn many things from that, this was really helpful for me. Thank you so much for sharing this info with us and share your ideas with us.
    AI Chatbot
    Chatbot Development
    RPA Bot
    Artificial Intelligence Company in Dubai

    ReplyDelete

Post a Comment

Best Programming language for machine learning.

Popular posts from this blog

Hackerrank - Dynamic Programming - The Coin Change Problem

Hackerrank - Implementation - Picking Numbers