using System;
class Program {
// Function to print a 2D array
static void Print(int[, ] arr, int N, int M)
{
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
Console.Write(arr[i, j] + " ");
}
Console.WriteLine();
}
}
// Function to compute the prefix sum of a 2D array
static void PrefixSum(int[, ] ARR, int N, int M)
{
int[, ] PRE = new int[N, M];
for (int i = 0; i < N; i++) {
for (int j = 0; j < M; j++) {
int x = 0;
int y = 0;
int z = 0;
// Calculate the sum of elements above the
// current element
if (i - 1 >= 0)
x = PRE[i - 1, j];
// Calculate the sum of elements to the left
// of the current element
if (j - 1 >= 0)
y = PRE[i, j - 1];
// Calculate the sum of elements in the
// diagonal (top-left)
if (i - 1 >= 0 && j - 1 >= 0)
z = PRE[i - 1, j - 1];
// Compute the prefix sum for the current
// element
PRE[i, j] = ARR[i, j] + x + y - z;
}
}
// Print the given array
Console.WriteLine("Given Array:");
Print(ARR, N, M);
// Print the computed prefix sum array
Console.WriteLine("Prefix Sum Array:");
Print(PRE, N, M);
}
// Driver code
static void Main()
{
int N = 4;
int M = 4;
int[, ] ARR = { { 1, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 1, 1, 1, 1 },
{ 1, 1, 1, 1 } };
// Function Call
PrefixSum(ARR, N, M);
}
}