## Problem: Bot saves princess

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 all the moves you take to rescue the princess in one go. The moves must be separated by ‘\n’, a newline. The valid outputs are LEFT or RIGHT or UP or DOWN.

Sample input

``````3
---
-m-
p--
``````

Sample output

``````DOWN
LEFT
``````

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

This is one of the methods:

#include <stdio.h>
#include <string.h>

#define MAX 100
void displayPathtoPrincess(int n, char grid[][MAX]){
//logic here
int i,j,m_i,m_j,p_i,p_j;
// find out the position of bot and princess
for(i=0;i<n;++i)
for(j=0;j<n;++j){
if(grid[i][j]==’m’){
m_i=i;
m_j=j;
}
if(grid[i][j]==’p’){
p_i=i;
p_j=j;
}
}
//draw into paper, you’ll see this situation has two cases
//first, the princess is lower than bot
if(p_i>m_i){
for(i=m_i;i<p_i;++i)
printf(“DOWN\n”);
if(p_j>m_j)
for(i=m_j;i<p_j;++i)
printf(“RIGHT\n”);
else
for(i=p_j;i<m_j;++i)
printf(“LEFT”);
}
//second, the princess is upper than bot
else{
for(i=p_i;i<m_i;++i)
printf(“UP\n”);
if(p_j>m_j)
for(i=m_j;i<p_j;++i)
printf(“RIGHT\n”);
else
for(i=p_j;i<m_j;++i)
printf(“LEFT”);
}
}
int main(){
int m;
scanf(“%d”, &m);
char grid[MAX][MAX];
char line[m];
for(int i=0; i<m; i++) {
scanf(“%s”, line);
strncpy(grid[i], line, m);
}
displayPathtoPrincess(m,grid);
return 0;
}