Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PYTHON

Prefix Sum of Matrix (Or 2D Array)

// C# program to find prefix
// sum of 2D array
using System;
 
class GFG
{
 
    // calculating new array
    static void prefixSum2D(int [,]a)
    {
        int R = a.GetLength(0);
        int C = a.GetLength(1);
 
        int [,]psa = new int[R, C];
 
        psa[0, 0] = a[0, 0];
 
        // Filling first row
        // and first column
        for (int i = 1; i < C; i++)
            psa[0, i] = psa[0, i - 1] +
                               a[0, i];
        for (int i = 1; i < R; i++)
            psa[i, 0] = psa[i - 1, 0] +
                               a[i, 0];
  
        // updating the values in the
        // cells as per the general formula.
        for (int i = 1; i < R; i++)
            for (int j = 1; j < C; j++)
 
                // values in the cells of
                // new array are updated
                psa[i, j] = psa[i - 1, j] +
                            psa[i, j - 1] -
                            psa[i - 1, j - 1] +
                            a[i, j];
 
        for (int i = 0; i < R; i++)
        {
            for (int j = 0; j < C; j++)
                Console.Write(psa[i, j] + " ");
            Console.WriteLine();
        }
    }
 
    // Driver Code
    static void Main()
    {
        int [,]a = new int[,]{{1, 1, 1, 1, 1},
                              {1, 1, 1, 1, 1},
                              {1, 1, 1, 1, 1},
                              {1, 1, 1, 1, 1}};
        prefixSum2D(a);
    }
}
 
// This code is contributed by manishshaw1
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #Prefix #Sum #Matrix
ADD COMMENT
Topic
Name
8+8 =