1789. Same-Value Square Frames
A tiling artist lays coloured tiles in a rectangular grid, where each cell holds a colour code from 0 to 9. A frame is an axis-aligned square of side s >= 2 cells whose border, all 4(s - 1) boundary cells, holds one single colour; the cells strictly inside may be anything. Squares are told apart by their position and side, so two frames with the same colour but different corners count separately.
Return the number of frames in grid as a long. Precompute for every cell how many equal values run to the right and how many run downwards, including the cell itself. The square with top-left corner (r, c) and side s is a frame exactly when the right run at (r, c) and at (r + s - 1, c) and the down run at (r, c) and at (r, c + s - 1) are all at least s. Enumerate every (r, c, s). Time is O(rows * cols * min(rows, cols)) and space is O(rows * cols).
Example 1
- Input:
- grid = [[1,1,1],[1,5,1],[1,1,1]]
- Output:
- 1
- Explanation:
Only the whole 3 by 3 board has a single-colour border; every 2 by 2 square contains the 5, so the count is 1.
Example 2
- Input:
- grid = [[2,2],[2,2]]
- Output:
- 1
- Explanation:
The single 2 by 2 square has all four cells equal, so the count is 1.
Example 3
- Input:
- grid = [[0,1,0],[1,0,1]]
- Output:
- 0
- Explanation:
No square of side 2 or more has a uniform border, so the count is 0.
Constraints
1 ≤ rows, cols ≤ 30; rows * cols ≤ 1000
0 ≤ grid[i][j] ≤ 9
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(rows * cols * min(rows, cols))
- Space
- O(rows * cols)