Problem solution · C++

Maximum Number of Points From Grid Queries

Maximum Number of Points From Grid Queries: a C++ solution using heap or priority queue. Learn the idea, check the complexity, and read the full code, with credit to walkccc LeetCode Solutions.

Technique
Heap or priority queue
Source
walkccc LeetCode Solutions
Length
66 lines
Start with the idea.

Try the problem first. If you get stuck, read the approach below, then write your own solution. The full code is at the bottom.

Approach

Heap or priority queue

For Maximum Number of Points From Grid Queries, the implementation repeatedly takes the currently best candidate from a heap while inserting newly available choices.

  1. Define the priority key and whether the smallest or largest item should lead.
  2. Push each candidate when it becomes eligible.
  3. Discard stale entries when necessary and process the best live candidate.

Code notes

  • 66 lines of C++ from the credited upstream file 2503.cpp.
  • The implementation visibly relies on sequence storage, work queue.
  • 4 loop blocks detected.

Complexity

Count heap pushes and pops; each normally contributes a logarithmic factor in the heap size.

Check the problem constraints before deciding whether this complexity will pass.

Source

Code and credit

This code comes from walkccc LeetCode Solutions by P.-Y. Chen (walkccc) and is used under the MIT licence.

Full codeMaximum Number of Points From Grid Queries · C++C++
Use this to learn the idea, then write your own version.
struct IndexedQuery {  int queryIndex;  int query;}; struct T {  int i;  int j;  int val;  // grid[i][j]}; class Solution { public:  vector<int> maxPoints(vector<vector<int>>& grid, vector<int>& queries) {    constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};    const int m = grid.size();    const int n = grid[0].size();    vector<int> ans(queries.size());    auto compare = [](const T& a, const T& b) { return a.val > b.val; };    priority_queue<T, vector<T>, decltype(compare)> minHeap(compare);    vector<vector<bool>> seen(m, vector<bool>(n));     minHeap.emplace(0, 0, grid[0][0]);    seen[0][0] = true;    int accumulate = 0;     for (const auto& [queryIndex, query] : getIndexedQueries(queries)) {      while (!minHeap.empty()) {        const auto [i, j, val] = minHeap.top();        minHeap.pop();        if (val >= query) {          // The smallest neighbor is still larger than `query`, so no need to          // keep exploring. Re-push (i, j, grid[i][j]) back to the `minHeap`.          minHeap.emplace(i, j, val);          break;        }        ++accumulate;        for (const auto& [dx, dy] : kDirs) {          const int x = i + dx;          const int y = j + dy;          if (x < 0 || x == m || y < 0 || y == n)            continue;          if (seen[x][y])            continue;          minHeap.emplace(x, y, grid[x][y]);          seen[x][y] = true;        }      }      ans[queryIndex] = accumulate;    }     return ans;  }  private:  vector<IndexedQuery> getIndexedQueries(const vector<int>& queries) {    vector<IndexedQuery> indexedQueries;    for (int i = 0; i < queries.size(); ++i)      indexedQueries.push_back({i, queries[i]});    ranges::sort(        indexedQueries, ranges::less{},        [](const IndexedQuery& indexedQuery) { return indexedQuery.query; });    return indexedQueries;  }}; 

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗