Maximal Rectangle [LeetCode]
Problem Description: Given a 2D binary matrix filled with 0's and 1's, find the largest rectangle containing all ones and return its area.
Basic idea: To increas one dimension by one, then calculate the maximum of other dimension every time.
1 class Solution { 2 public: 3 int maximalRectangle(vector<vector<char> > &matrix) { 4 // Note: The Solution object is instantiated only once and is reused by each test case. 5 if(matrix.size() == 0 || matrix[0].size() == 0) 6 return 0; 7 int max_area = 0; 8 int row = matrix.size(); 9 int column = matrix[0].size(); 10 for(int i = 0; i < row; i ++) { 11 for( int j = 0; j < column; j ++) { 12 if (matrix[i][j] == '0') 13 continue; 14 15 int tmp_area = 1; 16 int max_row_idx = row - 1; 17 int max_column_idx = j; 18 while(max_column_idx < column){ 19 int l; 20 for(l = i + 1; l <= max_row_idx; l ++){ 21 if (matrix[l][max_column_idx] == '0') 22 break; 23 } 24 max_row_idx = l - 1; 25 tmp_area = (max_row_idx - i + 1) * (max_column_idx - j + 1); 26 if(tmp_area > max_area) 27 max_area = tmp_area; 28 29 //increase column 30 if ( matrix[i][max_column_idx + 1] == '1'){ 31 max_column_idx ++; 32 }else{ 33 break; 34 } 35 } 36 37 } 38 } 39 return max_area; 40 } 41 };