Number Of Corner Rectangles - Problem
Given an m x n integer matrix grid where each entry is only 0 or 1, return the number of corner rectangles.
A corner rectangle is four distinct 1's on the grid that forms an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1's used must be distinct.
Input & Output
Example 1 — Basic Grid
$
Input:
grid = [[1,0,0,1],[0,0,1,0],[0,0,1,0]]
›
Output:
1
💡 Note:
There is 1 corner rectangle with corners at (0,0), (0,3), (2,0), and (2,3). Wait, (2,0)=0, so this is wrong. Let me recalculate: only valid rectangle is formed by rows 1 and 2 at columns 2, but we need 2 common columns. Actually grid[1][2]=1, grid[2][2]=1, but we need at least 2 columns with 1's in both rows.
Example 2 — Multiple Rectangles
$
Input:
grid = [[1,1,1],[1,1,1],[1,1,1]]
›
Output:
9
💡 Note:
Each pair of rows has 3 common columns with 1's. For each of 3 row pairs: C(3,2) = 3 rectangles. Total: 3 × 3 = 9 rectangles.
Example 3 — No Rectangles
$
Input:
grid = [[1,0],[0,1]]
›
Output:
0
💡 Note:
Only one pair of rows (0,1), but no columns have 1's in both rows, so no rectangles can be formed.
Constraints
- m == grid.length
- n == grid[i].length
- 1 ≤ m, n ≤ 200
- grid[i][j] is either 0 or 1
- The number of 1's in the grid is in the range [1, 6000]
Visualization
Tap to expand
Understanding the Visualization
1
Input Matrix
Binary matrix with 0's and 1's
2
Find Rectangles
Identify valid corner rectangles
3
Count Result
Total number of corner rectangles
Key Takeaway
🎯 Key Insight: Count rectangles efficiently by examining row pairs and finding columns where both rows have 1's
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code