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 )); // dp matrix
43
+ dp[n-1 ][m-1 ] = matrix[n-1 ][m-1 ]-' 0' ; // dp[n-][m-1] is same as matrix[n-1][m-1]
44
+ int ans = dp[n-1 ][m-1 ];
45
+ // last column is 1 or 0
46
+ for (int i=0 ;i<n-1 ;i++){
47
+ dp[i][m-1 ]=matrix[i][m-1 ]-' 0' ;
48
+ ans = max (ans, dp[i][m-1 ]);
49
+ }
50
+ // last row is 1 or 0
51
+ for (int j=0 ;j<m-1 ;j++){
52
+ dp[n-1 ][j]=matrix[n-1 ][j]-' 0' ;
53
+ ans = max (ans, dp[n-1 ][j]);
54
+ }
55
+ for (int i=n-2 ;i>=0 ;i--)
56
+ {
57
+ for (int j=m-2 ;j>=0 ;j--)
58
+ {
59
+ // dp[i][j] is 0 when matrix[i][j] is 0
60
+ if (matrix[i][j]==' 0' )
61
+ dp[i][j]=0 ;
62
+ // dp[i][j] is 1 + min(right_hand, diagonally_down, down)
63
+ else
64
+ dp[i][j] = 1 +min (dp[i][j+1 ],min (dp[i+1 ][j],dp[i+1 ][j+1 ]));
65
+ // ans is max of all values in dp
66
+ ans = max (dp[i][j], ans);
67
+ }
68
+ }
69
+ return ans*ans;
70
+ }
71
+
72
+ int main ()
73
+ {
74
+ int m,n;
75
+ cin>>m>>n;
76
+ vector<vector<char >>matrix (m, vector<char >(n, 0 ));
77
+ for (int i=0 ; i<m; i++)
78
+ {
79
+ for (int j=0 ; j<n; j++)
80
+ {
81
+ cin>>matrix[i][j];
82
+ }
83
+ }
84
+ // max. area of 1s
85
+ int ans = maximalSquare (matrix);
86
+ cout<<ans<<" \n " ;
87
+ }
0 commit comments