Building the 2D prefix array also uses inclusion-exclusion: 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]=0 and prefix[i][0]=0 for all i,j. This handles edge cases cleanly.