750 Number Of Corner Rectangles
1. Question
Given a grid where each entry is only 0 or 1, find the number of corner rectangles.
Acorner rectangleis 4 distinct 1s on the grid that form an axis-aligned rectangle. Note that only the corners need to have the value 1. Also, all four 1s used must be distinct.
Example 1:
Input: grid =
[[1, 0, 0, 1, 0],
[0, 0, 1, 0, 1],
[0, 0, 0, 1, 0],
[1, 0, 1, 0, 1]]
Output: 1
Explanation:
There is only one corner rectangle, with corners grid[1][2], grid[1][4], grid[3][2], grid[3][4].Example 2:
Input: grid =
[[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]
Output: 9
Explanation:
There are four 2x2 rectangles, four 2x3 and 3x2 rectangles, and one 3x3 rectangle.Example 3:
Note:
The number of rows and columns of
gridwill each be in the range[1, 200].Each
grid[i][j]will be either0or1.The number of
1s in the grid will be at most6000.
2. Implementation
(1)
思路: 1. 对于任意两行,找出它们在同一列都有1的个数count
2.然后我们从这些count中,任意选择两列作为矩形的边,根据组合公式,n里面取两个,公式为 n * (n - 1) /2
3. Time & Space Complexity
时间复杂度O(nm^2),m为矩形的行数,n为矩形的列数,空间复杂度O(1)
Last updated
Was this helpful?