Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CPP

Prefix Sum of Matrix (Or 2D Array)

<?php
// PHP Program to find
// prefix sum of 2d array
$R = 4;
$C = 5;
 
// calculating new array
function prefixSum2D($a)
{
    global $C, $R;
    $psa = array();
    $psa[0][0] = $a[0][0];
 
    // Filling first row
    // and first column
    for ($i = 1; $i < $C; $i++)
        $psa[0][$i] = $psa[0][$i - 1] +
                             $a[0][$i];
    for ($i = 0; $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 ($i = 1; $i < $R; $i++)
    {
        for ($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];
    }
 
    // displaying the values
    // of the new array
    for ($i = 0; $i < $R; $i++)
    {
        for ($j = 0; $j < $C; $j++)
            echo ($psa[$i][$j]. " ");
        echo ("
");
    }
}
 
// Driver Code
$a = array(array( 1, 1, 1, 1, 1 ),
           array( 1, 1, 1, 1, 1 ),
           array( 1, 1, 1, 1, 1 ),
           array( 1, 1, 1, 1, 1 ));
 
prefixSum2D($a);
 
// This code is contributed by
// Manish Shaw(manishshaw1)
?>
Source by www.geeksforgeeks.org #
 
PREVIOUS NEXT
Tagged: #Prefix #Sum #Matrix
ADD COMMENT
Topic
Name
3+5 =