Let's make this one less mysterious. For 1277. Count Square Submatrices with All Ones, the solution in this repository is mainly a dynamic programming solution.
Guide
What?
We want to turn the problem statement into a smaller set of decisions the computer can repeat safely. Instead of trying to be clever immediately, read the code as a sequence of questions:
- What state are we keeping?
- How do we move from one state to the next?
- When do we know the answer is already determined?
For this file, the main tools are: dynamic programming, two pointers.
Guide
When?
This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.
The important function names to track are countSquares.
Guide
Why?
The point of the implementation is not to make the code longer. It is to avoid doing the same thinking twice.
- The two-dimensional vector is the memory of the solution: grid state, DP state, or adjacency shape.
- The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.
Guide
How?
Walk through the solution in this order:
- Initialize the memory or helper structure.
- Process candidates in the order the invariant expects.
- Update the answer only when the current state is valid.
- Return the value that represents the fully processed input.
The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.
Guide
Complexity
- Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
- Space: O(n) in the usual case for auxiliary containers or recursion
Guide
C++ Solution
Your submission
The accepted solution
01//Runtime: 360 ms, faster than 16.09% of C++ online submissions for Count Square Submatrices with All Ones.
02//Memory Usage: 16 MB, less than 100.00% of C++ online submissions for Count Square Submatrices with All Ones.
03
04class Solution {
05public:
06 int countSquares(vector<vector<int>>& matrix) {
07 int m = matrix.size(), n = matrix[0].size();
08 int count = 0;
09
10 for(int len = 1; len <= min(m, n); len++){
11 for(int i = 0; i < m-(len-1); i++){
12 for(int j = 0; j < n-(len-1); j++){
13 bool valid = true;
14 for(int si = 0; si < len; si++){
15 for(int sj = 0; sj < len; sj++){
16 if(!matrix[i+si][j+sj]){
17 valid = false;
18 break;
19 }
20 }
21 if(!valid) break;
22 }
23 if(valid)count++;
24 }
25 }
26 }
27
28 return count;
29 }
30};
31
32//DP, O(N^2)
33//https://leetcode.com/problems/count-square-submatrices-with-all-ones/discuss/441306/Python-DP-solution
34//Runtime: 76 ms, faster than 36.81% of C++ online submissions for Count Square Submatrices with All Ones.
35//Memory Usage: 16 MB, less than 100.00% of C++ online submissions for Count Square Submatrices with All Ones.
36
37class Solution {
38public:
39 int countSquares(vector<vector<int>>& matrix) {
40 int m = matrix.size(), n = matrix[0].size();
41 int count = 0;
42
43 for(int i = 0; i < m; i++){
44 for(int j = 0; j < n; j++){
45 if(i > 0 && j > 0 && matrix[i][j]){
46 matrix[i][j] = min({matrix[i-1][j], matrix[i][j-1], matrix[i-1][j-1]}) + 1;
47 }
48 /*
49 matrix[i][j]:
50 the maximum length of square ends at (i, j).
51 suppose the length of the square we find is l,
52 we can find out the square(of size 1 to 1) ends at (i, j) is just l!
53 */
54 count += matrix[i][j];
55 }
56 }
57 return count;
58 }
59};
60
61//DP, O(n^3)
62//Hint 1: Create an additive table that counts the sum of elements of submatrix with the superior corner at (0,0).
63//Hint 2: Loop over all subsquares in O(n^3) and check if the sum make the whole array to be ones, if it checks then add 1 to the answer.
64//Runtime: 1980 ms, faster than 5.08% of C++ online submissions for Count Square Submatrices with All Ones.
65//Memory Usage: 26.5 MB, less than 100.00% of C++ online submissions for Count Square Submatrices with All Ones.
66class Solution {
67public:
68 int countSquares(vector<vector<int>>& matrix) {
69 int m = matrix.size();
70 if(m == 0) return 0;
71 int n = matrix[0].size();
72 if(n == 0) return 0;
73
74 /*
75 padding a row and a column ahead
76 so submatrixSum[i][j] corresponds to matrix[i-1][j-1]
77 */
78 vector<vector<int>> sms(m+1, vector(n+1, 0)); //submatrixSum
79
80 for(int i = 1; i <= m; i++){
81 for(int j = 1; j <= n; j++){
82 /*
83 submatrix down to prev row + submatrix right to prev column - submatrix to its left-top
84 plus
85 current element
86 */
87 sms[i][j] += sms[i-1][j] + sms[i][j-1] - sms[i-1][j-1] + matrix[i-1][j-1];
88 // cout << sms[i][j] << " ";
89 }
90 // cout << endl;
91 }
92
93 int ans = 0;
94
95 for(int i = 1; i <= m; i++){
96 for(int j = 1; j <= n; j++){
97 //the length of the edge of the square
98 for(int len = 1; len <= min(i, j); len++){
99 /*
100 use sms[i][j] - sms[i-len][j] - sms[i][j-len] + sms[i-len][j-len] to
101 calculate the sum of matrix[i-len...i-1, j-len...j-1]
102 */
103 if(sms[i][j] - sms[i-len][j] - sms[i][j-len] + sms[i-len][j-len] == len * len){
104 // cout << "(" << i << ", " << j << "), length: " << len << endl;
105 ans++;
106 }
107 }
108 }
109 }
110
111 return ans;
112 }
113};
Cost