File tree Expand file tree Collapse file tree 1 file changed +9
-4
lines changed Expand file tree Collapse file tree 1 file changed +9
-4
lines changed Original file line number Diff line number Diff line change @@ -39,13 +39,15 @@ using namespace std;
39
39
int maximalSquare (vector<vector<char >>& matrix) {
40
40
int n = matrix.size ();
41
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' ;
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
44
int ans = dp[n-1 ][m-1 ];
45
+ // last column is 1 or 0
45
46
for (int i=0 ;i<n-1 ;i++){
46
47
dp[i][m-1 ]=matrix[i][m-1 ]-' 0' ;
47
48
ans = max (ans, dp[i][m-1 ]);
48
- }
49
+ }
50
+ // last row is 1 or 0
49
51
for (int j=0 ;j<m-1 ;j++){
50
52
dp[n-1 ][j]=matrix[n-1 ][j]-' 0' ;
51
53
ans = max (ans, dp[n-1 ][j]);
@@ -54,10 +56,13 @@ int maximalSquare(vector<vector<char>>& matrix) {
54
56
{
55
57
for (int j=m-2 ;j>=0 ;j--)
56
58
{
59
+ // dp[i][j] is 0 when matrix[i][j] is 0
57
60
if (matrix[i][j]==' 0' )
58
- dp[i][j]=0 ;
61
+ dp[i][j]=0 ;
62
+ // dp[i][j] is 1 + min(right_hand, diagonally_down, down)
59
63
else
60
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
61
66
ans = max (dp[i][j], ans);
62
67
}
63
68
}
You can’t perform that action at this time.
0 commit comments