class Solution:
    def highestRankedKItems(self, G, pricing, start, k):
        m, n = len(G), len(G[0])
        row, col = start
        node = (0, G[row][col], row, col)
        visited = set()
        visited.add((row, col))
        d = deque([node])
        ans = []

        while d:
            dist, cost, row, col = d.popleft()
            if pricing[0] <= cost <= pricing[1]:
                ans += [(dist, cost, row, col)]

            for x, y in (row - 1, col), (row + 1, col), (row, col - 1), (row, col + 1):
                if 0 <= x <= m-1 and 0 <= y <= n-1 and (x, y) not in visited and G[x][y] != 0:
                    d.append((dist + 1, G[x][y], x, y))
                    visited.add((x, y))

        ans = sorted(ans)

        return [[x, y] for _, _, x, y in ans[:k]]
class Solution {
    static class Quad
    {
        int x,y,price,dist;
        Quad(int x,int y,int price,int dist)
        {
            this.x=x;
            this.y=y;
            this.price=price;
            this.dist=dist;
        }
    }
    public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) {
        List<List<Integer>> ans=new LinkedList<>();
        PriorityQueue<Quad> pq=new PriorityQueue<>((a,b)->{
            if(a.dist!=b.dist)
                return a.dist-b.dist;
            if(a.price!=b.price)
                return a.price-b.price;
            if(a.x!=b.x)
                return a.x-b.x;
            return a.y-b.y;
        });
        bfs(grid,start[0],start[1],pricing[0],pricing[1],pq);
        while(!pq.isEmpty()&&k-->0)
        {
            Quad quad=pq.poll();
            List<Integer> temp=new LinkedList<>();
            temp.add(quad.x);
            temp.add(quad.y);
            ans.add(temp);
        }
        return ans;
    }
    void bfs(int[][] grid,int i,int j,int low,int high,PriorityQueue<Quad> pq)
    {
        Queue<int[]> queue=new LinkedList<>();
        int m=grid.length,n=grid[0].length;
        if(grid[i][j]>=low&&grid[i][j]<=high)
            pq.add(new Quad(i,j,grid[i][j],0));
        grid[i][j]=0;
        queue.add(new int[]{i,j});
        int dist=0;
        int dirs[][]={{1,0},{-1,0},{0,1},{0,-1}};
        while(!queue.isEmpty())
        {
            ++dist;
            int size=queue.size();
            while(size-->0)
            {
                int[] p=queue.poll();
                for(int[] dir:dirs)
                {
                    int newX=dir[0]+p[0];
                    int newY=dir[1]+p[1];
                    if(newX>=0&&newY>=0&&newX<m&&newY<n&&grid[newX][newY]!=0)
                    {
                        if(grid[newX][newY]>=low&&grid[newX][newY]<=high)
                            pq.add(new Quad(newX,newY,grid[newX][newY],dist));
                        queue.add(new int[]{newX,newY});
                        grid[newX][newY]=0;
                    }
                }
            }
            
        }
    }
   

}
K Highest Ranked Items Within a Price Range
You are given a 0-indexed 2D integer array grid of size m x n that represents a map of the items in a shop. The integers in the grid represent the following:


	0 represents a wall that you cannot pass through.
	1 represents an empty cell that you can freely move to and from.
	All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells.


It takes 1 step to travel between adjacent grid cells.

You are also given integer arrays pricing and start where pricing = [low, high] and start = [row, col] indicates that you start at the position (row, col) and are interested only in items with a price in the range of [low, high] (inclusive). You are further given an integer k.

You are interested in the positions of the k highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different:


	Distance, defined as the length of the shortest path from the start (shorter distance has a higher rank).
	Price (lower price has a higher rank, but it must be in the price range).
	The row number (smaller row number has a higher rank).
	The column number (smaller column number has a higher rank).


Return the k highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than k reachable items within the price range, return all of them.

&nbsp;
Example 1:

Input: grid = [[1,2,0,1],[1,3,0,1],[0,2,5,1]], pricing = [2,5], start = [0,0], k = 3
Output: [[0,1],[1,1],[2,1]]
Explanation: You start at (0,0).
With a price range of [2,5], we can take items from (0,1), (1,1), (2,1) and (2,2).
The ranks of these items are:
- (0,1) with distance 1
- (1,1) with distance 2
- (2,1) with distance 3
- (2,2) with distance 4
Thus, the 3 highest ranked items in the price range are (0,1), (1,1), and (2,1).


Example 2:

Input: grid = [[1,2,0,1],[1,3,3,1],[0,2,5,1]], pricing = [2,3], start = [2,3], k = 2
Output: [[2,1],[1,2]]
Explanation: You start at (2,3).
With a price range of [2,3], we can take items from (0,1), (1,1), (1,2) and (2,1).
The ranks of these items are:
- (2,1) with distance 2, price 2
- (1,2) with distance 2, price 3
- (1,1) with distance 3
- (0,1) with distance 4
Thus, the 2 highest ranked items in the price range are (2,1) and (1,2).


Example 3:

Input: grid = [[1,1,1],[0,0,1],[2,3,4]], pricing = [2,3], start = [0,0], k = 3
Output: [[2,1],[2,0]]
Explanation: You start at (0,0).
With a price range of [2,3], we can take items from (2,0) and (2,1). 
The ranks of these items are: 
- (2,1) with distance 5
- (2,0) with distance 6
Thus, the 2 highest ranked items in the price range are (2,1) and (2,0). 
Note that k = 3 but there are only 2 reachable items within the price range.


&nbsp;
Constraints:


	m == grid.length
	n == grid[i].length
	1 &lt;= m, n &lt;= 105
	1 &lt;= m * n &lt;= 105
	0 &lt;= grid[i][j] &lt;= 105
	pricing.length == 2
	2 &lt;= low &lt;= high &lt;= 105
	start.length == 2
	0 &lt;= row &lt;= m - 1
	0 &lt;= col &lt;= n - 1
	grid[row][col] &gt; 0
	1 &lt;= k &lt;= m * n


var highestRankedKItems = function(grid, pricing, start, k) {
    const m = grid.length;
    const n = grid[0].length;
    const dirs = [-1, 0, 1, 0, -1];

    const visited = [];

    for (let i = 0; i < m; ++i) {
        visited[i] = new Array(n).fill(false);
    }

    const [low, high] = pricing;

    const queue = [];

    queue.push([...start, 0]);

    const items = [];

    while (queue.length > 0) {
        const [row, col, dist] = queue.shift();

        if (visited[row][col]) continue;

        visited[row][col] = true;

        const price = grid[row][col];

        if (withinRange(price, low, high)) {
            items.push({ dist, price, row, col });
        }

        for (let i = 0; i < dirs.length - 1; ++i) {
            const neiRow = row + dirs[i];
            const neiCol = col + dirs[i + 1];

            if (withinBound(neiRow, neiCol) && !visited[neiRow][neiCol] && grid[neiRow][neiCol] != 0) {
                queue.push([neiRow, neiCol, dist + 1]);
            }
        }
    }

    items.sort(compareFunc);

    const res = [];

    for (let i = 0; i < Math.min(k, items.length); ++i) {
        const { dist, price, row, col } = items[i];

        res.push([row, col]);
    }

    return res;

    function withinRange(price, low, high) {
        return low <= price && price <= high;
    }

    function withinBound(row, col) {
        return row >= 0 && col >= 0 && row < m && col < n;
    }

    function compareFunc(a, b) {
        return a.dist - b.dist || a.price - b.price || a.row - b.row || a.col - b.col;
    }
};
class Solution {
public:
    struct cell
    {
        int dist;
        int cost;
        int row;
        int col;
    };
    struct compare
    {
        bool operator()(const cell &a, const cell &b)
        {
            if(a.dist != b.dist)
                return a.dist < b.dist;
            else if(a.cost != b.cost)
                return a.cost < b.cost;
            else if(a.row != b.row)
                return a.row < b.row;
            else
                return a.col < b.col;
        }
    };

    vector<vector<int>> highestRankedKItems(vector<vector<int>>& grid, vector<int>& pricing, vector<int>& start, int k) {
        int m=grid.size();
        int n=grid[0].size();

        queue<pair<int,int>>q;
        q.push({start[0],start[1]});

        vector<vector<bool>> vis(m,vector<bool>(n,false));
        vis[start[0]][start[1]]=true;

        int dx[4]={-1,0,1,0};
        int dy[4]={0,-1,0,1};
        int dist=0;

        priority_queue<cell,vector<cell>,compare> pq;
         while(!q.empty())
         {
             int size=q.size();
             while(size--)
             {
                 pair<int,int> p=q.front(); q.pop();
                 if(grid[p.first][p.second]!=1 && grid[p.first][p.second]>=pricing[0] && grid[p.first][p.second]<=pricing[1])
                 {
                     pq.push({dist,grid[p.first][p.second],p.first,p.second});

                     if(pq.size()>k)
                         pq.pop();
                }
                for(int k=0;k<4;k++)
                {
                    int x=p.first+dx[k];
                    int y=p.second+dy[k];

                    if(x>=0 && x<m && y>=0 && y<n && vis[x][y]==false && grid[x][y]!=0)
                    {
                        vis[x][y]=true;
                        q.push({x,y});
                    }
                }
            }
        dist++;
        }

        vector<vector<int>> ans;
        while(!pq.empty())
        {
        ans.push_back({pq.top().row,pq.top().col});
        pq.pop();
        }

    reverse(ans.begin(),ans.end());
    return ans;
    }
};