Given a chessboard with n rows and columns OR Given an integer n, compute the total number of axis-aligned squares in an n x n grid (i.e., a chessboard of side length n).
Given an integer n, compute the total number of axis-aligned squares in an n x n grid (i.e., a chessboard of side length n). As a follow-up, generalize the solution to an m x n grid and return the number of axis-aligned squares (not rectangles).
Input: n =8Output: 204Explanation: Sum of squares 1^2+2^2+...+8^2=204
If you thought the answer is 64, think again! :)
At first glance you might answer 64, because there are 8 × 8 unit squares. But that only counts 1×1 squares. Larger squares form by grouping adjacent unit squares: a k×k square can start at any of the (8 − k + 1) horizontal positions and any of the (8 − k + 1) vertical positions, so there are (8 − k + 1)^2 distinct k×k squares. For example:
1×1: 8 × 8 = 64
2×2: 7 × 7 = 49
3×3: 6 × 6 = 36
4×4: 5 × 5 = 25
5×5: 4 × 4 = 16
6×6: 3 × 3 = 9
7×7: 2 × 2 = 4
8×8: 1 × 1 = 1
So the total equals 1^2 + 2^2 + … + 8^2 = 64 + 49 + … + 1 = 204 squares.
For an n x n grid a k x k square can be placed in (n - k + 1)^2 different positions; summing that quantity for k = 1..n yields the total number of squares. The result has a compact closed-form: n * (n + 1) * (2*n + 1) / 6.
Example (n = 8):
k = 1 → (8 - 1 + 1)^2 = 8^2 = 64
k = 2 → 7^2 = 49
k = 3 → 6^2 = 36
k = 4 → 5^2 = 25
k = 5 → 4^2 = 16
k = 6 → 3^2 = 9
k = 7 → 2^2 = 4
k = 8 → 1^2 = 1
Summing these gives 64 + 49 + 36 + 25 + 16 + 9 + 4 + 1 = 204. As k increases the number of valid placements falls roughly as (n - k + 1)^2, which is why the total accumulates the sequence of square numbers.
classSolution {
public:int countSquares(int m, int n) {
int minv = std::min(m, n);
int ans =0;
for (int s =1; s <= minv; ++s) ans += (m - s +1) * (n - s +1);
return ans;
}
};
classSolution {
publicintcountSquares(int m, int n) {
int min = Math.min(m, n);
int ans = 0;
for (int s = 1; s <= min; s++) ans += (m - s + 1) * (n - s + 1);
return ans;
}
}
1
2
3
4
5
6
7
8
classSolution {
funcountSquares(m: Int, n: Int): Int {
val minv = kotlin.math.min(m, n)
var ans = 0for (s in1..minv) ans += (m - s + 1) * (n - s + 1)
return ans
}
}
1
2
3
4
5
6
7
classSolutionMN:
defcountSquares(self, m: int, n: int) -> int:
ans =0 mn = min(m, n)
for s in range(1, mn +1):
ans += (m - s +1) * (n - s +1)
return ans
1
2
3
4
5
6
7
8
9
10
pubstructSolution;
impl Solution {
pubfncount_squares(m: i32, n: i32) -> i32 {
let minv = std::cmp::min(m, n);
letmut ans =0i32;
for s in1..=minv { ans += (m - s +1) * (n - s +1); }
ans
}
}