Generate a matrix with each row and column of given sum | C ++ program for the above approach ; Function to generate a matrix with sum of each row equal to sum of r [ ] and sum of each column equal to sum of c [ ] ; Initialize a matrix ; Traverse each cell ( i , j ) of the matrix ; Assign the minimum of the row or column value ; Subtract the minimum from both row and column sum ; Print the matrix obtained ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; vector < vector < int > > restoreGem ( vector < int > & r , vector < int > & c ) { vector < vector < int > > dp ( r . size ( ) , vector < int > ( c . size ( ) , 0 ) ) ; for ( int i = 0 ; i < r . size ( ) ; i ++ ) { for ( int j = 0 ; j < c . size ( ) ; j ++ ) { int m = min ( r [ i ] , c [ j ] ) ; dp [ i ] [ j ] = m ; r [ i ] -= m ; c [ j ] -= m ; } } return dp ; } void printMatrix ( vector < vector < int > > ans , int N , int M ) { for ( int i = 0 ; i < N ; i ++ ) { for ( int j = 0 ; j < M ; j ++ ) { cout << ans [ i ] [ j ] << " ▁ " ; } cout << endl ; } } int main ( ) { vector < int > rowSum = { 5 , 7 , 10 } ; vector < int > colSum = { 8 , 6 , 8 } ; vector < vector < int > > ans = restoreGem ( rowSum , colSum ) ; printMatrix ( ans , rowSum . size ( ) , colSum . size ( ) ) ; }