Data Structures19 sections · 729 units
Open in Course

2D Prefix - Building

Construction formula

Building the 2D prefix array also uses inclusion-exclusion: prefix[i][j]=mat[i1][j1]+prefix[i1][j]+prefix[i][j1]prefix[i1][j1]prefix[i][j] = mat[i-1][j-1] + prefix[i-1][j] + prefix[i][j-1] - prefix[i-1][j-1] You add the current cell, plus the rectangle above, plus the rectangle to the left.

But the top-left rectangle gets counted twice, so subtract it once. Initialize prefix[0][j]=0prefix[0][j] = 0 and prefix[i][0]=0prefix[i][0] = 0 for all i,ji, j. This handles edge cases cleanly.