Sub-rectangles that sum to a target
Given a grid of integers grid (at least one row and one column; values may be negative) and an integer target, count the sub-rectangles whose cells add up to exactly target. A sub-rectangle is the block of cells from row r1 to r2 and column c1 to c2, all four bounds included; two sub-rectangles are different when any bound differs.
With r rows and c columns, trying every rectangle is O(r²c²). Aim for O(r²c), or O(c²r) when the grid has more rows than columns.
Besides the tests, one large input (an 8 × 720 grid) with a ~220 ms limit (scaled to your device's speed): brute force won't pass.
Examples
count_target_rects([[1,0,1],[0,-1,0]], 0)→5count_target_rects([[2,-1],[-1,2]], 1)→4count_target_rects([[2,1,3],[1,2,0]], 3)→7