1. 程式人生 > >19.2.23 [LeetCode 85] Maximal Rectangle

19.2.23 [LeetCode 85] Maximal Rectangle

n) 當前 ret example -s hid turn 技術 style

Given a 2D binary matrix filled with 0‘s and 1‘s, find the largest rectangle containing only 1‘s and return its area.

Example:

Input:
[
  ["1","0","1","0","0"],
  ["1","0","1","1","1"],
  ["1","1","1","1","1"],
  ["1","0","0","1","0"]
]
Output: 6

題意

找圖中由1組成的最大矩形

題解

技術分享圖片
 1 class Solution {
 2 public
: 3 int maximalRectangle(vector<vector<char>>& matrix) { 4 if (matrix.empty())return 0; 5 int m = matrix.size(), n = matrix[0].size(), ans = 0; 6 vector<int>height(n, 0),left(n, 0), right(n, n); 7 for (int i = 0; i < m; i++) { 8 int
s = 0; 9 for (int j = 0; j < n; j++) { 10 if (matrix[i][j] == 0) { 11 height[j] = 0; 12 left[j] = 0; 13 s = j + 1; 14 } 15 else { 16 left[j] = max(left[j], s);
17 height[j]++; 18 } 19 } 20 int e = n - 1; 21 for (int j = n - 1; j >= 0; j--) { 22 if (matrix[i][j] == 0) { 23 right[j] = n; 24 e = j - 1; 25 } 26 else { 27 right[j] = min(right[j], e); 28 } 29 } 30 for (int j = 0; j < n; j++) 31 if (matrix[i][j] == 1) 32 ans = max(ans, (right[j] - left[j] + 1)*height[j]); 33 } 34 return ans; 35 } 36 };
View Code

這題好難的……

思路是找到三個數組 height[x] 代表從當前行的x索引表示的元素往上數能數到多少連續的1, left[x] 表示當前行的x索引往左邊數能數到多少個連續的height值>=它自己的1, right[x] 與left相仿(這些計數均包括當前索引且如果當前索引的值為0則這三個數組相應的值無意義)

19.2.23 [LeetCode 85] Maximal Rectangle