#196 · Lists · Expert · 260 XP · about 50 min
grid is a rectangle of integers stored as a list of rows. Write count_submatrices(grid, target) that counts the rectangular blocks of the grid whose values add up to target.
A block is any choice of neighbouring rows and neighbouring columns, from a single cell up to the whole grid, and blocks in different places count separately. Values can be negative or zero.
count_submatrices([[0, 1, 0], [1, 1, 1], [0, 1, 0]], 0) # returns 4 count_submatrices([[1, -1], [-1, 1]], 0) # returns 5 count_submatrices([[904]], 0) # returns 0
In the second example the five blocks are the two rows, the two columns and the whole grid.
-1,000 and 1,000target is between -10**8 and 10**8Ready?
Accept the challenge to start writing. A small timer counts the time this page is in view.
Output appears here.