Leetcode 221. Maximal Square
本题用brute force超时。可以用DP,也可以不用。
dp[i][j] 代表 以(i,j)为右下角正方形的边长。
1 class Solution(object): 2 def maximalSquare(self, matrix): 3 """ 4 :type matrix: List[List[str]] 5 :rtype: int 6 """ 7 if not matrix: 8 return 0 9 10 m = len(matrix) 11 n = len(matrix[0]) 12 res = 0 13 dp = [[0 for x in range(n)] for y in range(m)] 14 15 for i in range(m): 16 if matrix[i][0] == '1': 17 dp[i][0] = 1 18 res = 1 19 20 for j in range(n): 21 if matrix[0][j] == '1': 22 dp[0][j] = 1 23 res = 1 24 25 for i in range(1,m): 26 for j in range(1,n): 27 if matrix[i][j] == '1': 28 dp[i][j] = min(dp[i-1][j-1], min(dp[i-1][j],dp[i][j-1])) + 1 29 res = max(res, dp[i][j]) 30 31 return res * res