Replace each Matrix element with its row product except that element - GeeksforGeeks

17 Jan, 2022
Given a 2D-array mat[][] of order M*N. The task is to replace every element of each row with the product of other elements of the same row.
Examples: 
Input: mat[][] = {{3, 4, 1}, {6, 1, 7}, {2, 9, 8}}Output:4, 3, 127, 42, 672, 16, 18             
Input: mat[][] = {{13, 4, 5}, {6, 11, 1}}Output:20, 65, 5211, 6, 66
Approach: The idea is straightforward. Traverse the matrix row-wise and find the product of each row. In the second traversal find the replacement value for each cell of the row. Follow the steps below to solve the problem:
Initialize the variables mul, i and j.
Iterate over the range [0, M) using the variable i and perform the following tasks:Set the value of mul as 1.Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mul as mul*mat[i][j].Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mat[i][j] as mul/mat[i][j].
Set the value of mul as 1.
Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mul as mul*mat[i][j].
Set the value of mul as mul*mat[i][j].
Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mat[i][j] as mul/mat[i][j].
Set the value of mat[i][j] as mul/mat[i][j].
After performing the above steps, print the values of mat[][] as the answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;const int M = 3, N = 3; // Show Matrix.void showMatrix(vector<vector<int> >& mat){    int i, j;    for (i = 0; i < M; i++) {        for (j = 0; j < N; j++) {            cout << mat[i][j] << " ";        }        cout << endl;    }} // Utility Functionvoid ReplaceWithProduct(vector<vector<int> >& mat){    int mul, i, j;    for (i = 0; i < M; i++) {        mul = 1;        for (j = 0; j < N; j++)            mul *= mat[i][j];        for (j = 0; j < N; j++)            mat[i][j] = mul / mat[i][j];    }    showMatrix(mat);} // Utility Main function.int main(){    vector<vector<int> > mat = { { 3, 6, 2 },                                 { 1, 4, 9 },                                 { 5, 3, 8 } };    ReplaceWithProduct(mat);    return 0;}
// Java program for the above approachimport java.util.*;public class GFG{  static int M = 3, N = 3;   // Show Matrix.  static void showMatrix(int [][]mat)  {    int i, j;    for (i = 0; i < M; i++) {      for (j = 0; j < N; j++) {        System.out.print(mat[i][j] + " ");      }      System.out.println();    }  }   // Utility Function  static void ReplaceWithProduct(int [][]mat)  {    int mul, i, j;    for (i = 0; i < M; i++) {      mul = 1;      for (j = 0; j < N; j++)        mul *= mat[i][j];      for (j = 0; j < N; j++)        mat[i][j] = mul / mat[i][j];    }    showMatrix(mat);  }   // Utility Main function.  public static void main(String args[])  {    int [][]mat = { { 3, 6, 2 },                   { 1, 4, 9 },                   { 5, 3, 8 } };    ReplaceWithProduct(mat);   }} // This code is contributed by Samim Hossain Mondal.
# python3 program for the above approachM = 3N = 3 # Show Matrix.def showMatrix(mat):     for i in range(0, M):        for j in range(0, N):            print(mat[i][j], end=" ")         print() # Utility Functiondef ReplaceWithProduct(mat):     for i in range(0, M):        mul = 1        for j in range(0, N):            mul *= mat[i][j]        for j in range(0, N):            mat[i][j] = mul // mat[i][j]     showMatrix(mat) # Utility Main function.if __name__ == "__main__":     mat = [[3, 6, 2],           [1, 4, 9],           [5, 3, 8]]    ReplaceWithProduct(mat) # This code is contributed by rakeshsahni
// C# program for the above approachusing System;public class GFG{  static int M = 3, N = 3;   // Show Matrix.  static void showMatrix(int [,]mat)  {    int i, j;    for (i = 0; i < M; i++) {      for (j = 0; j < N; j++) {        Console.Write(mat[i,j] + " ");      }      Console.WriteLine();    }  }   // Utility Function  static void ReplaceWithProduct(int [,]mat)  {    int mul, i, j;    for (i = 0; i < M; i++) {      mul = 1;      for (j = 0; j < N; j++)        mul *= mat[i,j];      for (j = 0; j < N; j++)        mat[i,j] = mul / mat[i,j];    }    showMatrix(mat);  }   // Utility Main function.  public static void Main(String []args)  {    int [,]mat = { { 3, 6, 2 },                   { 1, 4, 9 },                   { 5, 3, 8 } };    ReplaceWithProduct(mat);   }} // This code is contributed by 29AjayKumar
<script>      // JavaScript code for the above approach       let M = 3, N = 3;       // Show Matrix.      function showMatrix(mat) {          let i, j;          for (i = 0; i < M; i++) {              for (j = 0; j < N; j++) {                  document.write(mat[i][j] + " ");              }              document.write('<br>')          }      }       // Utility Function      function ReplaceWithProduct(mat) {          let mul, i, j;          for (i = 0; i < M; i++) {              mul = 1;              for (j = 0; j < N; j++)                  mul *= mat[i][j];              for (j = 0; j < N; j++)                  mat[i][j] = mul / mat[i][j];          }          showMatrix(mat);      }       // Utility Main function.       let mat = [[3, 6, 2],      [1, 4, 9],      [5, 3, 8]];      ReplaceWithProduct(mat); // This code is contributed by Potta Lokesh  </script>
12 6 18 
36 9 4 
24 40 15
 
Time Complexity: O(N*N)Auxiliary Space: O(1)
lokeshpotta20
samim2000
rakeshsahni
29AjayKumar
Algo-Geek 2021
Algo Geek
Matrix
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Sort strings on the basis of their numeric part
Smallest set of vertices to visit all nodes of the given Graph
Divide given number into two even parts
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Program to find largest element in an array
Matrix Chain Multiplication | DP-8
Rat in a Maze | Backtracking-2
Breadth First Traversal ( BFS ) on a 2D array
Print a given matrix in spiral form