Program to find matrix for which rows and columns holding sum of behind rows and columns in Python

PythonServer Side ProgrammingProgramming

Suppose we have a given matrix, We have to find a new matrix res, whose dimension is same as the given matrix where each element in res[i, j] = sum of the elements of matrix[r, c] for each r ≤ i, and c ≤ j.

So, if the input is like

82
74

then the output will be

810
1521

To solve this, we will follow these steps −

  • if matrix is empty, then

    • return matrix

  • R := row count of matrix

  • C := column count of matrix

  • for r in range 1 to R - 1, do

    • for c in range 0 to C - 1, do

      • matrix[r, c] := matrix[r, c] + matrix[r - 1, c]

  • for r in range 0 to R - 1, do

    • for c in range 1 to C - 1, do

      • matrix[r, c] := matrix[r, c] + matrix[r, c - 1]

  • return matrix

Example

Let us see the following implementation to get better understanding

def solve(matrix):
   if not matrix:
      return matrix

   R, C = len(matrix), len(matrix[0])
   for r in range(1, R):
         for c in range(C):
            matrix[r][c] += matrix[r - 1][c]

   for r in range(R):
      for c in range(1, C):
         matrix[r][c] += matrix[r][c - 1]

   return matrix

matrix = [
   [8, 2],
   [7, 4]
]
print(solve(matrix))

Input

[[8, 2],[7, 4]]

Output

[[8, 10], [15, 21]]
raja
Published on 11-Oct-2021 08:16:23
Advertisements