Approach
Breadth-first search
For Maximum Number of Points From Grid Queries, the implementation explores reachable states in layers, which is the standard shape for unweighted shortest paths and minimum-step transitions.
- Model each valid configuration as a state and each legal move as an edge.
- Seed the queue with the starting state and mark it immediately.
- Expand each state once, recording distance or reachability for unseen neighbours.
Code notes
- 56 lines of Java from the credited upstream file 2503.java.
- The implementation visibly relies on sequence storage, work queue.
- 4 loop blocks detected.
Complexity
Verify that each state and transition is processed only a bounded number of times; that determines the traversal cost.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public int[] maxPoints(int[][] grid, int[] queries) {3 record T(int i, int j, int val) {}4 final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};5 final int m = grid.length;6 final int n = grid[0].length;7 int[] ans = new int[queries.length];8 Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::val));9 boolean[][] seen = new boolean[m][n];10 11 minHeap.offer(new T(0, 0, grid[0][0]));12 seen[0][0] = true;13 int accumulate = 0;14 15 for (IndexedQuery indexedQuery : getIndexedQueries(queries)) {16 final int queryIndex = indexedQuery.queryIndex;17 final int query = indexedQuery.query;18 while (!minHeap.isEmpty()) {19 final int i = minHeap.peek().i;20 final int j = minHeap.peek().j;21 final int val = minHeap.poll().val;22 if (val >= query) {23 24 25 minHeap.offer(new T(i, j, val));26 break;27 }28 ++accumulate;29 for (int[] dir : DIRS) {30 final int x = i + dir[0];31 final int y = j + dir[1];32 if (x < 0 || x == m || y < 0 || y == n)33 continue;34 if (seen[x][y])35 continue;36 minHeap.offer(new T(x, y, grid[x][y]));37 seen[x][y] = true;38 }39 }40 ans[queryIndex] = accumulate;41 }42 43 return ans;44 }45 46 private record IndexedQuery(int queryIndex, int query) {}47 48 private IndexedQuery[] getIndexedQueries(int[] queries) {49 IndexedQuery[] indexedQueries = new IndexedQuery[queries.length];50 for (int i = 0; i < queries.length; ++i)51 indexedQueries[i] = new IndexedQuery(i, queries[i]);52 Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::query));53 return indexedQueries;54 }55}56