Forest Queries

You are given an n × n grid called forest representing a forest map. Each cell contains either "*" (a tree) or "." (empty).

The grid uses 1-based indexing: the top-left cell is (1,1) and the bottom-right cell is (n,n).

You are also given a list of queries query, where each query is of the form [x1, y1, x2, y2].

For every query, determine the number of trees ("*" cells) inside the rectangle defined by:

  • Top-left corner: (x1, y1)
  • Bottom-right corner: (x2, y2)

The rectangle boundaries are inclusive.

Return an array of integers where the ith element represents the answer to the ith query.

Example 1:

Input: forest = [["*", "."], [".", "*"]], query = [[1, 1, 2, 2]]

Output: [2]

Explanation: The rectangle covers the entire grid. There are 2 trees.

Example 2:

Input: forest = [["*", "*", "."], [".", "*", "."], ["*", ".", "."]], query = [[1, 1, 2, 2], [2, 2, 3, 3]]

Output: [3, 1]

Explanation:

  • Query 1 → rectangle (1,1) to (2,2): contains 3 trees
  • Query 2 → rectangle (2,2) to (3,3): contains 1 tree

Now Your Turn!

Pick the correct output for the given input

Input: forest = [[".", "*", "."], ["*", "*", "."], [".", ".", "*"]], query = [[1, 2, 3, 3]]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 ≤ n ≤ 1000
  • 1 ≤ q ≤ 2 · 105
  • 1 ≤ y1 ≤ y2 ≤ n
  • 1 ≤ x1 ≤ x2 ≤ n

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
class Solution {
public:
vector<int> queryForest(vector<vector<string>> &forest, vector<vector<int>> &query) {
// Your code goes here
}
};
Test Case

Input:

Forest
Query