All problems

Problem 446

Count Square Submatrices with All Ones

Medium · 20 pts · Matrix, Dynamic Programming

Problem

Count the square submatrices that consist entirely of 1s in a 0/1 matrix. Squares of every size count: each single cell with value 1 is a 1 x 1 square, and larger squares count separately. Let side[i][j] be the size of the largest all-ones square whose bottom-right corner is at (i, j); then the cell contributes side[i][j] squares, and side[i][j] = 1 + min(side above, side to the left, side diagonally above-left) for cells with value 1.

Input

First line: R and C. Next R lines: C values, each 0 or 1.

Output

Print the number of all-ones square submatrices.

Constraints

1 <= R, C <= 300

Example input

3 4
0 1 1 1
1 1 1 1
0 1 1 1

Example output

15

Explanation

The matrix 0 1 1 1 / 1 1 1 1 / 0 1 1 1 contains ten 1 x 1 squares, four 2 x 2 squares and one 3 x 3 square: 15 in total.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Minimum ASCII Delete Sum Next: Maximal Rectangle