221. 最大正方形

221. 最大正方形

在一个由 0 和 1 组成的二维矩阵内,找到只包含 1 的最大正方形,并返回其面积。

示例:

输入: 

1 0 1 0 0
1 0 1 1 1
1 1 1 1 1
1 0 0 1 0

输出: 4

思路

遍历所有项,当遇到1的时候,先往右下搜索,碰到1的话,再搜索这个斜角位置左边和上边是否都为1而能组成正方形,若可以则继续搜索,搜索完后与res取最大值,不断更新搜索就行了。

class Solution:
    def maximalSquare(self, matrix):
        """
        :type matrix: List[List[str]]
        :rtype: int
        """

        res = 0

        for i in range(len(matrix)):
            for j in range(len(matrix[0])):
                if matrix[i][j] == '1':
                    tp = 1;
                    x = i+1;y = j+1;a = 0;
                    if x<len(matrix) and y<len(matrix[0]):
                        while matrix[x][y] == '1' :
                            a+=1;f = 1;tp2=0
                            while matrix[x-f][y] == '1' and matrix[x][y-f]=='1' and f<=a:
                                tp2 += 2
                                f += 1
                            if tp2/2 != a: 
                                break
                            tp = (a+1)**2
                            x +=1;y+=1
                            if x>=len(matrix) or y>=len(matrix[0]):
                                break
                    res = max(tp,res)
        return res



猜你喜欢

转载自blog.csdn.net/qq_21567767/article/details/82316869