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:
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:
Input: grid = [[1, 1, 1, 1]] Output: 0 Explanation: Rectangles must have four distinct corners.
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
.
思路:肯定不能像下面2个那样一个个数
class Solution:
def countCornerRectangles(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
ret=0
n,m=len(grid),len(grid[0])
for i in range(n):
for j in range(m):
if grid[i][j]==0: continue
for ii in range(i+1, n):
if grid[ii][j]==0: continue
for jj in range(j+1, m):
if grid[i][j]+grid[ii][j]+grid[i][jj]+grid[ii][jj]==4:
ret+=1
return ret
s=Solution()
print(s.countCornerRectangles([[1, 1, 1],
[1, 1, 1],
[1, 1, 1]]))
class Solution:
def countCornerRectangles(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
ret=0
n,m=len(grid),len(grid[0])
s,l=set(),[]
for i in range(n):
for j in range(m):
if grid[i][j]==1:
s.add(200*i+j)
l.append(200*i+j)
for i in range(len(l)):
for j in range(i+1,len(l)):
if l[i]>=l[j]: continue
r1,c1,r2,c2=l[i]//200,l[i]%200,l[j]//200,l[j]%200
if r1>=r2 or c1>=c2: continue
if r1*200+c2 in s and r2*200+c1 in s:
ret += 1
return ret
思路:容易想到的是n*(n-1)/2这个计算公式,先固定2行,求每列与这2行相交是不是都是1 ,计算这样的列数
class Solution:
def countCornerRectangles(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
ret=0
for i in range(len(grid)-1):
for j in range(i+1,len(grid)):
cnt = 0
for k in range(len(grid[0])):
if grid[i][k]+grid[j][k]==2:
cnt += 1
ret += cnt*(cnt-1)//2
return ret
Python超时,但是Java AC
Python还需要改变遍历方式做一点prune
counts[i][j] is used to keep track of the number of rows, found so far, in which column i and column j are 1.
Every time you find a new row that has i and j set to 1, counts will tell you how many rectangles you can form with this new row.
def countCornerRectangles(self, grid):
res = 0
counts = [[0] * len(grid[rows]) for rows in range(len(grid))]
for row in range(0, len(grid)):
for j in range(1, len(grid[0])):
if grid[row][j] == 1:
for i in range(0, j):
if grid[row][i] == 1:
res += counts[i][j]
counts[i][j] += 1
return int(res)