1
+ /*
2
+ Question => https://leetcode.com/problems/maximal-square/
3
+
4
+ Description:
5
+ Given an m x n binary matrix filled with 0's and 1's, find the largest square containing only 1's and return its area.
6
+
7
+ Eg:
8
+ m = 4 and n = 5
9
+
10
+ 1 0 1 0 0
11
+ 1 0 |1 1| 1
12
+ 1 1 |1 1| 1
13
+ 1 0 0 1 0
14
+
15
+ The answer here is: 4 (2x2) shown here
16
+
17
+ Soltuion:
18
+
19
+ The approach is to use dynamic programming.
20
+ We use another matrix to store the maximal square possible using the (i,j)-th element of matrix
21
+ as the bottom-left corner of the matrix.
22
+ Base cases :
23
+ a) Fill the left-most column with 1 and (0 where matrix is 0) dp[i][n-1]=1 or 0
24
+ b) Fill the bottom-most row with 1 and (0 where matrix is 0). dp[m-1][i]=1 or 0
25
+ Then for general case:
26
+ dp[i][j] = 0 => if matrix[i][j]=0
27
+ dp[i][j] = 1 + min(dp[i+1][j], dp[i+1][j+1], dp[i][j+1])
28
+ for matrix[i][j]=> dp[i][j] is 1 + minimum of cell on right, bottom and diagonally right
29
+
30
+ The answer is the max. value in the dp matrix.
31
+
32
+ */
33
+
34
+ // The code for the solution =>
35
+
36
+ #include < bits/stdc++.h>
37
+ using namespace std ;
38
+
39
+ int maximalSquare (vector<vector<char >>& matrix) {
40
+ int n = matrix.size ();
41
+ int m = matrix[0 ].size ();
42
+ vector<vector<int >>dp (n, vector<int >(m, 0 ));
43
+ dp[n-1 ][m-1 ] = matrix[n-1 ][m-1 ]-' 0' ;
44
+ int ans = dp[n-1 ][m-1 ];
45
+ for (int i=0 ;i<n-1 ;i++){
46
+ dp[i][m-1 ]=matrix[i][m-1 ]-' 0' ;
47
+ ans = max (ans, dp[i][m-1 ]);
48
+ }
49
+ for (int j=0 ;j<m-1 ;j++){
50
+ dp[n-1 ][j]=matrix[n-1 ][j]-' 0' ;
51
+ ans = max (ans, dp[n-1 ][j]);
52
+ }
53
+ for (int i=n-2 ;i>=0 ;i--)
54
+ {
55
+ for (int j=m-2 ;j>=0 ;j--)
56
+ {
57
+ if (matrix[i][j]==' 0' )
58
+ dp[i][j]=0 ;
59
+ else
60
+ dp[i][j] = 1 +min (dp[i][j+1 ],min (dp[i+1 ][j],dp[i+1 ][j+1 ]));
61
+ ans = max (dp[i][j], ans);
62
+ }
63
+ }
64
+ return ans*ans;
65
+ }
66
+
67
+ int main ()
68
+ {
69
+ int m,n;
70
+ cin>>m>>n;
71
+ vector<vector<char >>matrix (m, vector<char >(n, 0 ));
72
+ for (int i=0 ; i<m; i++)
73
+ {
74
+ for (int j=0 ; j<n; j++)
75
+ {
76
+ cin>>matrix[i][j];
77
+ }
78
+ }
79
+ // max. area of 1s
80
+ int ans = maximalSquare (matrix);
81
+ cout<<ans<<" \n " ;
82
+ }
0 commit comments