Given a 2D grid
of 0
s and 1
s, return the number of elements in the largest square subgrid that has all 1
s on its border, or 0
if such a subgrid doesn't exist in the grid
.
Example 1:
Input: grid = [[1,1,1],[1,0,1],[1,1,1]] Output: 9
Example 2:
Input: grid = [[1,1,0,0]] Output: 1
Constraints:
1 <= grid.length <= 100
1 <= grid[0].length <= 100
grid[i][j]
is0
or1
思路:brute force的解法很简单,直接从大到小遍历所有可能的结果,但是复杂度到了10^8,会TLE
一个优化的思路是:预先计算出matrix的每个(i,j)位置求出能往4个方向扩展的最大长度(taolu),复杂度10^6
class Solution(object):
def largest1BorderedSquare(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
n,m=len(grid),len(grid[0])
# up
expand_up = [[0 for _ in range(m)] for _ in range(n)]
expand_up[0] = grid[0]
for i in range(1,n):
for j in range(m):
if grid[i][j]==0: continue
expand_up[i][j] = expand_up[i-1][j]+1
#down
expand_down = [[0 for _ in range(m)] for _ in range(n)]
expand_down[n-1] = grid[n-1]
for i in range(n-2,-1,-1):
for j in range(m):
if grid[i][j]==0: continue
expand_down[i][j] = expand_down[i+1][j]+1
# left
expand_left = [[0 for _ in range(m)] for _ in range(n)]
for i in range(n): expand_left[i][0] = grid[i][0]
for i in range(n):
for j in range(1,m):
if grid[i][j]==0: continue
expand_left[i][j] = expand_left[i][j-1]+1
# right
expand_right = [[0 for _ in range(m)] for _ in range(n)]
for i in range(n): expand_right[i][m-1] = grid[i][m-1]
for i in range(n):
for j in range(m-2,-1,-1):
if grid[i][j]==0: continue
expand_right[i][j] = expand_right[i][j+1]+1
def ok(x):
for i in range(0,n-x+1):
for j in range(0,m-x+1):
expand_ul=min([expand_right[i][j], expand_down[i][j]])
expand_ur=min([expand_left[i][j+x-1],expand_down[i][j+x-1]])
expand_bl=min([expand_right[i+x-1][j],expand_up[i+x-1][j]])
expand_br=min([expand_left[i+x-1][j+x-1],expand_up[i+x-1][j+x-1]])
if min([expand_ul,expand_ur,expand_bl,expand_br])>=x:
return True
return False
for i in range(min(n,m),0,-1):
if ok(i): return i*i
return 0