private static long[,] tiltedIntegral3(byte[,] img)
{
int rows = img.GetLength(0);
int cols = img.GetLength(1);
int val = 0;
var expected = new long[rows + 2, cols + 2];
for (int y = 1; y < rows + 2; y++)
{
for (int x = 2; x < cols + 2; x++)
{
long r = val;
// if (y - 1 >= 0 && x - 1 >= 0)
r += expected[y - 1, x - 1];
// if (y >= 0 && x - 1 >= 0)
r += expected[y, x - 1];
if (y - 1 >= 0 && x - 1 >= 0 && y - 1 < rows && x - 2 < cols)
r += img[y - 1, x - 2];
//if (y - 1 >= 0 && x - 2 >= 0)
r -= expected[y - 1, x - 2];
expected[y, x] = r;
}
}
for (int y = rows + 1; y >= 0; y--)
{
for (int x = cols + 1; x >= 0; x--)
{
long r = expected[y, x];
if (y + 1 < rows + 2 && x - 1 >= 0)
r += expected[y + 1, x - 1];
if (y >= 0 && x - 2 >= 0)
r -= expected[y, x - 2];
expected[y, x] = r;
}
}
return expected;
}