Skip to content

Instantly share code, notes, and snippets.

@surajhande
Created December 26, 2018 09:56
Show Gist options
  • Save surajhande/e0f363a7d33556f578d0e52b093d1ddf to your computer and use it in GitHub Desktop.
Save surajhande/e0f363a7d33556f578d0e52b093d1ddf to your computer and use it in GitHub Desktop.
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <functional>
using namespace std;
#define ROWS 4
#define COLS 4
int g_map[ROWS][COLS];
int g_length[ROWS][COLS];
bool isLast(int i, int j)
{
int top = g_map[(i - 1) >= 0 ? i - 1 : i][j];
int bottom = g_map[(i + 1) < ROWS ? i + 1 : i][j];
int right = g_map[i][(j + 1) < COLS ? j + 1 : j];
int left = g_map[i][(j - 1) >= 0 ? j - 1 : j];
int curr = g_map[i][j];
if (top >= curr && bottom >= curr && right >= curr && left >= curr)
return true;
else
return false;
}
int solve(int i, int j, int&first, int& last)
{
if (isLast(i, j))
{
g_length[i][j] = 1;
last = g_map[i][j];
return g_length[i][j];
}
else
{
int top = (i - 1) >= 0 ? i - 1 : i;
int bottom = (i + 1) < ROWS ? i + 1 : i;
int right = (j + 1) < COLS ? j + 1 : j;
int left = (j - 1) >= 0 ? j - 1 : j;
int curr = g_map[i][j];
int top_sol, bottom_sol, right_sol, left_sol;
std::map<int, int, std::greater<int>> localBestPath;
if (curr > g_map[top][j])
{
top_sol = solve(top, j, first, last);
localBestPath.insert(make_pair((first - last), last));
}
if (curr > g_map[bottom][j])
{
bottom_sol = solve(bottom, j, first, last);
localBestPath.insert(make_pair((first - last), last));
}
if (curr > g_map[i][left])
{
left_sol = solve(i, left, first, last);
localBestPath.insert(make_pair((first - last), last));
}
if (curr > g_map[i][right])
{
right_sol = solve(i, right, first, last);
localBestPath.insert(make_pair((first - last), last));
}
g_length[i][j] = 1 + max(max(top_sol, bottom_sol), max(right_sol, left_sol));
last = localBestPath.begin()->second; // pick the last visited step of the best path
return g_length[i][j];
}
}
int main()
{
int rows = 0, cols = 0;
map<int /*length*/, int /*drop*/, std::greater<int>> bestPath;
cin >> rows;
cin >> cols;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
g_length[i][j] = -1;
cin >> g_map[i][j];
}
}
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
int last = 0; // stores the last visited step
solve(i, j, g_map[i][j], last);
map<int, int>::iterator it = bestPath.find(g_length[i][j]);
if (it == bestPath.end())
bestPath.insert(make_pair(g_length[i][j], g_map[i][j] - last));
else
it->second = ((g_map[i][j] - last) > it->second) ? g_map[i][j] - last : it->second;
}
}
cout << bestPath.begin()->first << bestPath.begin()->second;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment