Difference array in two dimensions
Updated
Range-add v on (r1, c1, r2, c2) is four writes on d: d[r1][c1]+=v, d[r1][c2+1]-=v, d[r2+1][c1]-=v, d[r2+1][c2+1]+=v. d is (n+1)×(m+1). Then 2D-prefix rebuild fills a.
What to focus on
Start a at zeros. Overlapping updates just accumulate on d. One rebuild at the end, not after each update.
Worked examples
full add 3
a = [[0, 0], [0, 0]], add 3 on (0,0)-(1,1)- d[0][0]+=3, d[0][2]-=3, d[2][0]-=3, d[2][2]+=3
- rebuild P[0][0]=3, P[0][1]=3, P[1][0]=3, P[1][1]=3
Result: [[3, 3], [3, 3]]
one cell
a = [[0, 0], [0, 0]], add 4 on (1,1)-(1,1)- d[1][1]+=4, d[1][2]-=4, d[2][1]-=4, d[2][2]+=4
- rebuild P[1][1]=4, rest 0
Result: [[0, 0], [0, 4]]
overlap
a = [[0, 0], [0, 0]], +1 on row0 (0,0)-(0,1), +2 on col1 (0,1)-(1,1)- four writes then four more on d
- rebuild [[1, 3], [0, 2]]
Result: [[1, 3], [0, 2]]
Try it
Write rangeAdd2D(d, r1, c1, r2, c2, v). d is a (rows+1)×(cols+1) difference matrix. (r1, c1, r2, c2) is the inclusive rectangle. v is the amount to add. Do the four writes, then one 2D-prefix rebuild. Return a. 2×2 zeros +3 everywhere → [[3, 3], [3, 3]] +4 at (1, 1) → [[0, 0], [0, 4]] +1 on row 0 and +2 on col 1 → [[1, 3], [0, 2]]
a starts as a non-empty zero matrix. 0 ≤ r1 ≤ r2 < rows and 0 ≤ c1 ≤ c2 < cols. d is (rows+1)×(cols+1).