#include <bits/stdc++.h>
using namespace std;
int minAbsoluteValue(vector<vector<int> >& arr)
{
int N = arr.size(), M = arr[0].size();
// priority queue containing pairs of cells and their
// respective distance from the source cell in the form
// {diff, {row of cell, col of cell}}
priority_queue<pair<int, pair<int, int> >,
vector<pair<int, pair<int, int> > >,
greater<pair<int, pair<int, int> > > >
pq;
// distance matrix with initially all the cells marked
// as unvisited
vector<vector<int> > d(N, vector<int>(M, 1e9));
// distance for source cell (0,0) is 0
d[0][0] = 0;
pq.push({ 0, { 0, 0 } });
// array to traverse in all four directions
int dx[] = { -1, 0, 1, 0 };
int dy[] = { 0, 1, 0, -1 };
// Iterate through the matrix by popping the elements
// out of the queue and pushing whenever a shorter
// distance to a cell is found
while (!pq.empty()) {
int diff = pq.top().first;
int r = pq.top().second.first;
int c = pq.top().second.second;
pq.pop();
// return the current value of difference (which
// will be min) if we reach the destination
if (r == N - 1 && c == M - 1)
return diff;
for (int i = 0; i < 4; i++) {
// r-1, c
// r, c+1
// r-1, c
// r, c-1
int nx = dx[i] + r;
int ny = dy[i] + c;
// checking validity of the cell
if (nx >= 0 && nx < N && ny >= 0 && ny < M) {
// effort can be calculated as the max value
// of differences between the values of the
// node and its adjacent nodes
int nf = max(abs(arr[r][c] - arr[nx][ny]),
diff);
// if the calculated effort is less than the
// prev value update as we need the min
// effort
if (nf < d[nx][ny]) {
d[nx][ny] = nf;
pq.push({ nf, { nx, ny } });
}
}
}
}
// if unreachable
return -1;
}
// Driver Code
int main()
{
// Example 1
vector<vector<int> > arr
= { { 1, 2, 2 }, { 3, 8, 2 }, { 5, 3, 5 } };
cout << minAbsoluteValue(arr) << endl;
// Example 2
arr = { { 1, 2, 1, 1, 1 },
{ 1, 2, 1, 2, 1 },
{ 1, 2, 1, 2, 1 },
{ 1, 1, 1, 2, 1 } };
cout << minAbsoluteValue(arr) << endl;
return 0;
}