PROBLEM LINK:
Practice
Contest: Division 1
Contest: Division 2
Contest: Division 3
Contest: Division 4
Author: iceknight1093
Tester: raysh07
Editorialist: iceknight1093
DIFFICULTY:
Cakewalk
PREREQUISITES:
None
PROBLEM:
Given an N\times M binary grid, find the smallest area of a rectangle that contains all the ones in the grid.
EXPLANATION:
The constraints are small, so brute force works.
However, there is a smarter solution.
Let l denote the leftmost column that contains a 1, and r denote the rightmost column that contains a 1.
Similarly, let u and d denote the uppermost and lowermost rows that contain a 1.
Then, observe that for the rectangle we choose:
- All columns from l to r must be included; if not we’ll miss some 1.
- All rows from u to d must be included; if not we’ll miss some 1.
- Columns \lt l or \gt r are not important, similarly rows \lt u or \gt d are not important.
Thus, it’s optimal to just take all columns from l to r and rows from u to d.
The area of this rectangle is just (r-l+1) \cdot (d-u+1).
TIME COMPLEXITY:
\mathcal{O}(NM) per testcase.
CODE:
Editorialist's code (PyPy3)
for _ in range(int(input())):
n, m = map(int, input().split())
grid = [input() for i in range(n)]
l, r, u, d = m, 0, n, 0
for i in range(n):
for j in range(m):
if grid[i][j] == '1':
l = min(l, j)
r = max(r, j)
u = min(u, i)
d = max(d, i)
print((r-l+1) * (d-u+1))