For this question on leetcode, using `dijkstra`

algo :

You are a hiker preparing for an upcoming hike. You are given heights, a 2D array of size rows x columns, where heights[row][col] represents the height of cell (row, col). You are situated in the top-left cell, (0, 0), and you hope to travel to the bottom-right cell, (rows-1, columns-1) (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort.

A route's effort is the maximum absolute difference in heights between two consecutive cells of the route.

Return the minimum effort required to travel from the top-left cell to the bottom-right cell.

**I am getting TLE time limit exceeded if I use priority_queue with struct. Can anyone help me figure out the reason?**

TLE code :

```
struct heapNode
{
int w;
int i;
int j;
heapNode(int n1, int n2, int n3) : w(n1), i(n2), j(n3)
{
}
};
struct Comp {
bool operator()(heapNode const& p1, heapNode const& p2)
{
// return "true" if "p1" is ordered
// before "p2", for example:
return p1.w < p2.w;
}
};
class Solution {
public:
int minimumEffortPath(vector<vector<int>>& heights) {
int r = heights.size(), c = heights[0].size();
int dirs[5] = {-1, 0, 1, 0, -1};
priority_queue<heapNode,vector<heapNode>,Comp> minheap;
vector<vector<int>> effort(r,vector<int>(c,INT_MAX));
// effort[0][0] = 0;
minheap.push(heapNode(0,0,0));
while(!minheap.empty())
{
auto top = minheap.top(); minheap.pop();
int w = top.w;
int i = top.i;
int j = top.j;
if (w >= effort[i][j]) continue;
effort[i][j] = w;
for(int k = 0;k<4;k++)
{
int x = i + dirs[k], y = j + dirs[k + 1];
if(x>=0 && y>=0 && x<r && y<c)
{
int t = max(w, abs(heights[i][j] - heights[x][y]));
minheap.push(heapNode(t,x,y));
}
}
}
return effort[r-1][c-1];
}
};
```

Working Code :

```
using pii = pair<int,int>;
class Solution {
public:
int minimumEffortPath(vector<vector<int>>& heights) {
int r = heights.size(), c = heights[0].size();
int dirs[5] = {-1, 0, 1, 0, -1};
priority_queue<pii,vector<pii>,greater<pii>> minheap;
vector<vector<int>> effort(r,vector<int>(c,INT_MAX));
effort[0][0] = 0;
minheap.push({effort[0][0],0});
while(!minheap.empty())
{
auto top = minheap.top(); minheap.pop();
int w = top.first;
int i = top.second / 100, j = top.second % 100;
for(int k = 0;k<4;k++)
{
int x = i + dirs[k], y = j + dirs[k + 1];
if(x>=0 && y>=0 && x<r && y<c)
{
if(effort[x][y] > max(w, abs(heights[i][j] - heights[x][y])))
{
effort[x][y] = max(w, abs(heights[i][j] - heights[x][y]));
minheap.push({effort[x][y],x*100+y});
}
}
}
}
return effort[r-1][c-1];
}
};
```

Read more here: https://stackoverflow.com/questions/68489746/using-custom-comparator-for-priority-queue-increases-time-c

### Content Attribution

This content was originally published by lupin at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.