Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to Find Out the Number of Squares in a Grid in Python
Suppose we have two values p and q, we have to find the number of unique squares that can be generated from a grid with p rows and q columns in which the points are placed evenly. If the answer is very large return result mod 10^9 + 7.
In this problem, a square is a set of 4 points that form the four vertices of a square. The sides of the square must have the same length, and it does not always have to be aligned with the axes of the grid.
So, if the input is like p = 4, q = 4, then the output will be 20.
Approach
To solve this, we will follow these steps ?
For each possible side length
ifrom 0 to minimum of (rows-1, columns-1)Calculate squares of side length
i:(r - i) * (c - i) * iSum all possibilities and return result mod (10^9 + 7)
Example
Let us see the following implementation to get better understanding ?
class Solution:
def solve(self, r, c):
ans = 0
for i in range(min(r, c)):
ans += (r - i) * (c - i) * i
return ans % (10 ** 9 + 7)
# Test the solution
ob = Solution()
print(ob.solve(4, 4))
The output of the above code is ?
20
How It Works
For a 4×4 grid:
When i = 0: No squares (side length 0)
When i = 1: (4-1) × (4-1) × 1 = 9 unit squares
When i = 2: (4-2) × (4-2) × 2 = 8 squares of side length 2
When i = 3: (4-3) × (4-3) × 3 = 3 squares of side length 3
Total: 0 + 9 + 8 + 3 = 20 squares
Alternative Implementation
Here's a more concise function-based approach ?
def count_squares(rows, cols):
"""Count unique squares in a grid"""
MOD = 10**9 + 7
total = 0
for side_length in range(min(rows, cols)):
squares_of_this_size = (rows - side_length) * (cols - side_length) * side_length
total += squares_of_this_size
return total % MOD
# Test with different grid sizes
print(f"4x4 grid: {count_squares(4, 4)} squares")
print(f"3x5 grid: {count_squares(3, 5)} squares")
print(f"2x2 grid: {count_squares(2, 2)} squares")
The output of the above code is ?
4x4 grid: 20 squares 3x5 grid: 13 squares 2x2 grid: 1 squares
Conclusion
This algorithm efficiently counts all possible squares in a grid by iterating through each possible side length and calculating how many squares of that size can fit. The time complexity is O(min(rows, cols)) making it very efficient for large grids.
