1605. Find Valid Matrix Given Row and Column Sums #76
-
You are given two arrays Find any matrix of non-negative integers of size Return a 2D array representing any matrix that fulfills the requirements. It's guaranteed that at least one matrix that fulfills the requirements exists. Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
To solve this problem, we can follow these steps:
Let's implement this solution in PHP: 1605. Find Valid Matrix Given Row and Column Sums <?PHP
function restoreMatrix($rowSum, $colSum) {
$m = count($rowSum);
$n = count($colSum);
$matrix = array_fill(0, $m, array_fill(0, $n, 0));
for ($i = 0; $i < $m; $i++) {
for ($j = 0; $j < $n; $j++) {
$val = min($rowSum[$i], $colSum[$j]);
$matrix[$i][$j] = $val;
$rowSum[$i] -= $val;
$colSum[$j] -= $val;
}
}
return $matrix;
}
// Example usage:
$rowSum1 = [3, 8];
$colSum1 = [4, 7];
print_r(restoreMatrix($rowSum1, $colSum1));
// Output: [[3, 0], [1, 7]]
$rowSum2 = [5, 7, 10];
$colSum2 = [8, 6, 8];
print_r(restoreMatrix($rowSum2, $colSum2));
// Output: [[0, 5, 0], [6, 1, 0], [2, 0, 8]]
?> Explanation:
This method ensures that the constructed matrix meets the row and column sum requirements while maintaining non-negative values for all elements. |
Beta Was this translation helpful? Give feedback.
To solve this problem, we can follow these steps:
rowSum.length x colSum.length
initialized with zeros.(i, j)
, place the minimum value betweenrowSum[i]
andcolSum[j]
to ensure non-negative values.rowSum[i]
andcolSum[j]
by subtracting the placed value.rowSum
andcolSum
are zero.Let's implement this solution in PHP: 1605. Find Valid Matrix Given Row and Column Sums