Bot Saves Princess

Received a message from HackerRank with the following [edited] content:

Bot saves princess

Artificial Intelligence | 31,989 submissions

An introduction to bot challenges.

Rescue the princess trapped in the corner of the grid.

If interested take a look at the challenge using the following URL:  https://www.hackerrank.com/challenges/saveprincess?utm_campaign=challenge-recommendation&utm_medium=email&utm_source=24-hour-campaign

Following is a screen dump of the Eclipse IDE console using the sample data:

3

-m-

p–

DOWN

LEFT

I created an additional test using the following data:

5

—-p

—–

–m–

—–

—–

UP

RIGHT

UP

RIGHT

The Java code for the solution follows:

import java.util.Scanner;

public class Solution {

static void printPath(int n, String moves) {

for (int i = n / 2; i >= 0; i -= 2) {

System.out.println(moves);

}

}

static void displayPathtoPrincess(int n, String [] grid){

// **** princess @ top left  ****

if (grid[0].substring(0, 1).equals(“p”)) {

printPath(n, “UP\nLEFT”);

}

// **** princess @ top right ****

else if (grid[0].substring(n – 1, n).equals(“p”) ) {

printPath(n, “UP\nRIGHT”);

}

// **** princess @ bottom right ****

else if (grid[n – 1].substring(n – 1, n).equals(“p”)) {

printPath(n, “DOWN\nRIGHT”);

}

// **** princess @ bottom left ****

else {

printPath(n, “DOWN\nLEFT”);

}

}

public static void main(String[] args) {

Scanner in = new Scanner(System.in);

int m;

m = in.nextInt();

String grid[] = new String[m];

for(int i = 0; i < m; i++) {

grid[i] = in.next();

}

// **** ****

in.close();

// **** ****

displayPathtoPrincess(m,grid);

}

}

If you have comments or questions regarding this or any other post in this blog please do not hesitate and send me a message. I will respond as soon as possible and will not mention your name unless you explicitly allow me to do so.

John

john.canessa@gmail.com

Follow me on Twitter:  @john_canessa

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.