750 Number Of Corner Rectangles
Given a grid where each entry is only 0 or 1, find the number of corner rectangles.
A corner rectangle is 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:
Example 2:
Example 3:
Note:
The number of rows and columns of
grid
will each be in the range[1, 200]
.Each
grid[i][j]
will be either0
or1
.The number of
1
s in the grid will be at most6000
.
Hint : For each pair of 1s in the new row (say at new_row[i]
and new_row[j]
), we could create more rectangles where that pair forms the base. The number of new rectangles is the number of times some previous row had row[i] = row[j] = 1
.
这题,不看hint完全没想法。看了答案也花了很长时间理解。其实,brute force的实现就是这样,每次找下一行。找的时候,发现了1,就去找同行里其他的1,找到两个1之后,往上找,看上面有没有同样位置也是1的。这里用了hashmap来存,每次加完记得更新hashmap。编码方式跟graph Queue的一样,i * m + j。T:O(R*C^2),S:O(C^2)
Last updated