首页 > 代码库 > Maximal Square

Maximal Square

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

Example

For example, given the following matrix:

1 0 1 0 01 0 1 1 11 1 1 1 11 0 0 1 0

Return 4.

 

Analyse: Let dp[i][j] represents the maximum side of a square whose right bottom element is matrix[i][j]. 

dp[i][j] = min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1])) + 1

Runtime: 124ms

 1 class Solution { 2 public: 3     /** 4      * @param matrix: a matrix of 0 and 1 5      * @return: an integer 6      */ 7     int maxSquare(vector<vector<int> > &matrix) { 8         // write your code here 9         if (matrix.empty() || matrix[0].empty()) return 0;10         11         int m = matrix.size(), n = matrix[0].size();12         vector<vector<int> > dp(m, vector<int>(n, 0));13         14         int result = 0;15         // initialize the first row16         for (int i = 0; i < n; i++) {17             if (matrix[0][i]) {18                 dp[0][i] = 1;19                 result = 1;20             }21         }22         23         // initialize the first column24         for (int i = 0; i < m; i++) {25             if (matrix[i][0]) {26                 dp[i][0] = 1;27                 result = 1;28             }29         }30         31         // calculate the remaining part32         for (int i = 1; i < m; i++) {33             for (int j = 1; j < n; j++) {34                 if (matrix[i][j]) {35                     dp[i][j] = min(dp[i][j - 1], min(dp[i - 1][j], dp[i - 1][j - 1])) + 1;36                     result = max(result, dp[i][j]);37                 }38                 else dp[i][j] = 0;39             }40         }41         return result * result;42     }43 };

 

Maximal Square