Problem Description
Given an m x n binary matrix, count the number of corner rectangles. A corner rectangle is defined as a group of four distinct 1’s that form the corners of an axis-aligned rectangle in the grid. Note that only the corners need to have the value 1.
Key Insights
- Only the four corner positions need to be 1, and the rectangle edges are aligned with the axes.
- Instead of checking every possible rectangle, iterate over pairs of rows.
- For every pair of rows, count the columns where both rows have a 1.
- If there are k columns with 1’s in both rows, there are k choose 2 possible rectangles using that row pair.
- The problem reduces to summing k*(k-1)/2 over all row pairs.
Space and Time Complexity
Time Complexity: O(m^2 * n)
Space Complexity: O(1)
Solution
The solution leverages the insight that a valid rectangle is determined by a pair of rows that share at least two columns containing 1’s. For each pair of rows, traverse every column to count the columns in which both rows have a 1. With k such columns, the number of rectangles formed is given by the combination formula k * (k - 1) / 2. Sum the rectangles from all row pairs to obtain the total count.