Maximal Square

Posted amazingzoe

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 0
1 0 1 1 1
1 1 1 1 1
1 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 row
16         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 column
24         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 part
32         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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] Maximal Square

221. Maximal Square

Maximal Square

Maximal Square

221. Maximal Square

221. Maximal Square