[leetcode]@python 85. Maximal Rectangle
生活随笔
收集整理的這篇文章主要介紹了
[leetcode]@python 85. Maximal Rectangle
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接
https://leetcode.com/problems/maximal-rectangle/
題目原文
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
題目大意
給出一個包含0和1的矩陣,在矩陣中找到一個矩形,這個矩形只包含1
解題思路
道題需要利用上一道題(Largest Rectangle in Histogram)的結論。比如對于以下矩陣。
0 0 0 0
0 0 1 0
0 1 1 0
1 0 1 1
對于這個矩陣,對于每一行,我們按照上一道題的算法求解一遍,最后得出的就是最大的矩陣。
代碼
class Solution(object):def largestRectangleArea(self, heights):""":type heights: List[int]:rtype: int"""stack = []i = 0area = 0while i < len(heights):if stack == [] or heights[i] > heights[stack[len(stack) - 1]]:stack.append(i)else:cur = stack.pop()if stack == []:width = ielse:width = i - stack[len(stack) - 1] - 1area = max(area, width * heights[cur])i -= 1i += 1while stack != []:cur = stack.pop()if stack == []:width = ielse:width = len(heights) - stack[len(stack) - 1] - 1area = max(area, width * heights[cur])return areadef maximalRectangle(self, matrix):""":type matrix: List[List[str]]:rtype: int"""if matrix == []:return 0a = [0 for i in range(len(matrix[0]))]maxArea = 0for i in range(len(matrix)):for j in range(len(matrix[i])):if matrix[i][j] == '1':a[j] = a[j] + 1else:a[j] = 0maxArea = max(maxArea, self.largestRectangleArea(a))return maxArea轉載于:https://www.cnblogs.com/slurm/p/5179572.html
總結
以上是生活随笔為你收集整理的[leetcode]@python 85. Maximal Rectangle的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Google Chrome v48.0.
- 下一篇: JAVA Socket 底层是怎样基于T