Created
January 17, 2013 15:25
-
-
Save pdu/4556704 to your computer and use it in GitHub Desktop.
Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area. http://leetcode.com/onlinejudge#question_85
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Solution { | |
| public: | |
| int maximalRectangle(vector<vector<char> > &matrix) { | |
| int n = matrix.size(); | |
| if (0 == n) | |
| return 0; | |
| int m = matrix[0].size(); | |
| if (0 == m) | |
| return 0; | |
| int **f; | |
| f = new int*[n]; | |
| for (int i = 0; i < n; ++i) | |
| f[i] = new int[m]; | |
| for (int i = 0; i < n; ++i) | |
| for (int j = 0; j < m; ++j) | |
| f[i][j] = matrix[i][j] - '0' + (j > 0 ? f[i][j - 1] : 0); | |
| int sz = 0; | |
| int ret = 0; | |
| for (int k = 0; k < m; ++k) { | |
| sz = (m - k) * n; | |
| if (sz <= ret) | |
| break; | |
| for (int t = m - 1; t >= k; --t) { | |
| sz = (t - k + 1) * n; | |
| if (sz <= ret) | |
| break; | |
| int beg = -1; | |
| int end = -1; | |
| for (int i = 0; i < n; ++i) | |
| if (f[i][t] - (k > 0 ? f[i][k - 1] : 0) == t - k + 1) { | |
| if (beg == -1) | |
| beg = i; | |
| end = i; | |
| } | |
| else { | |
| if (beg != -1) | |
| ret = max(ret, (t - k + 1) * (end - beg + 1)); | |
| beg = -1; | |
| } | |
| if (beg != -1) | |
| ret = max(ret, (t - k + 1) * (end - beg + 1)); | |
| } | |
| } | |
| for (int i = 0; i < n; ++i) | |
| delete[] f[i]; | |
| delete[] f; | |
| return ret; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
can you provide explanation