Header Ad

HackerEarth JP and the Escape Plan problem solution

In this HackerEarth JP and the Escape Plan problem solution JP is stuck in a grid of buildings of size N X M, after he is dropped from a helicopter. He will be able to escape this grid if he can reach to any building that is on the boundary of grid. He can jump from one building to the other if and only if :

The buildings shares the edges with each other, i.e are adjacent (not diagonally adjacent)
The building to which he is jumping should be of the same height of the building on which he is standing OR the building to which he is jumping should have height at max J less than the one on which he is standing.
The top left building will have the co-ordinates (1,1) and the bottom right will have the co-ordinates (N,M)


HackerEarth JP and the Escape Plan problem solution


HackerEarth JP and the Escape Plan problem solution.

#include<bits/stdc++.h>
using namespace std;
#define MAX 505
#define pb push_back
#define mp make_pair
#define pi pair <int, int>
#define ff first
#define ss second

int mat[MAX][MAX];
bool vis[MAX][MAX];
int n, m, max_jump;
vector <pi> path;

bool solve(int old_i, int old_j, int i, int j)
{
if(i < 0 or i >= n or j < 0 or j >= m) //out of bounds
return 0;
if(vis[i][j])
return 0;
if(mat[old_i][old_j]-mat[i][j] > max_jump or mat[old_i][old_j] < mat[i][j])
return 0;
if(i == 0 or i == n-1 or j == 0 or j == m-1) //boundary
{
path.pb(mp(i, j));
return 1;
}
vis[i][j] = 1;
if(solve(i, j, i+1, j) || solve(i, j, i-1, j) || solve(i, j, i, j+1) || solve(i, j, i, j-1))
{
path.pb(mp(i, j));
return 1;
}
return 0;
}

void printPath()
{
for(int i = path.size()-1 ; i > -1 ; i--)
cout << path[i].ff+1 << " " << path[i].ss+1 << endl;
path.clear();
}

bool isBoundary(int i, int j) //JP can be dropped on a boundary building too
{
if(i == 0 or i == n-1 or j == 0 or j == m-1)
return 1;
return 0;
}

int main()
{
int t;
cin >> t;
while(t--)
{
memset(vis, 0, sizeof(vis));
cin >> n >> m;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
cin >> mat[i][j];

int drop_i, drop_j;
cin >> drop_i >> drop_j >> max_jump;
drop_i--;
drop_j--;
vis[drop_i][drop_j] = 1;
if(isBoundary(drop_i, drop_j) || solve(drop_i, drop_j, drop_i+1, drop_j) || solve(drop_i, drop_j, drop_i, drop_j+1) || solve(drop_i, drop_j, drop_i-1, drop_j) || solve(drop_i, drop_j, drop_i, drop_j-1))
{
path.pb(mp(drop_i, drop_j));
cout << "YES" << endl;
printPath();
}
else
cout << "NO" << endl;
}
return 0;
}

Post a Comment

0 Comments