Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find valid matrix given row and column sums in Python
Suppose we have two arrays rowSum and colSum with non-negative values where rowSum[i] has the sum of the elements in the ith row and colSum[j] has the sum of the elements in the jth column of a 2D matrix. We have to find any matrix with non-negative values of size (rowSum size x colSum size) that satisfies the given rowSum and colSum values.
So, if the input is like rowSum = [13,14,12] and colSum = [9,13,17], then the output will be ?
| 9 | 4 | 0 |
| 0 | 9 | 5 |
| 0 | 0 | 12 |
Algorithm
To solve this, we will follow these steps ?
- Create an empty matrix of size (rows × columns)
- Keep track of visited rows and columns
- Find the minimum value among unvisited row sums and column sums
- If minimum is from a row, assign it to the first available column in that row
- If minimum is from a column, assign it to the first available row in that column
- Update the corresponding row/column sums and mark as visited
- Repeat until all rows and columns are processed
Implementation
def solve(rowSum, colSum):
# Create a copy to avoid modifying original arrays
r = rowSum.copy()
c = colSum.copy()
# Initialize matrix with zeros
matrix = [[0] * len(c) for _ in range(len(r))]
visited = set()
def find_minimum():
min_total = float('inf')
type_min = ''
index = -1
# Find minimum among row sums
for i in range(len(r)):
if r[i] < min_total:
index = i
type_min = 'row'
min_total = r[i]
# Find minimum among column sums
for i in range(len(c)):
if c[i] < min_total:
min_total = c[i]
type_min = 'col'
index = i
# Process the minimum value
if type_min == 'row':
r[index] = float('inf')
for i in range(len(c)):
if c[i] != float('inf') and c[i] >= min_total:
c[i] -= min_total
matrix[index][i] = min_total
break
elif type_min == 'col':
c[index] = float('inf')
for i in range(len(r)):
if r[i] != float('inf') and r[i] >= min_total:
r[i] -= min_total
matrix[i][index] = min_total
break
visited.add((index, type_min))
# Continue until all rows and columns are processed
while len(visited) != len(r) + len(c):
find_minimum()
return matrix
# Test the function
rowSum = [13, 14, 12]
colSum = [9, 13, 17]
result = solve(rowSum, colSum)
print("Generated matrix:")
for row in result:
print(row)
The output of the above code is ?
Generated matrix: [9, 4, 0] [0, 9, 5] [0, 0, 12]
How It Works
The algorithm works by greedily selecting the minimum value from the remaining row and column sums. This ensures that we can always find a valid assignment:
- Initialize: Create a zero matrix and copy the input arrays
- Find minimum: Compare all unprocessed row and column sums
- Assign value: Place the minimum value in the appropriate matrix position
- Update sums: Subtract the assigned value from corresponding row/column sum
- Mark as processed: Set the processed sum to infinity to exclude it
Verification Example
def verify_matrix(matrix, original_rowSum, original_colSum):
# Verify row sums
for i, row in enumerate(matrix):
if sum(row) != original_rowSum[i]:
return False, f"Row {i} sum mismatch"
# Verify column sums
for j in range(len(matrix[0])):
col_sum = sum(matrix[i][j] for i in range(len(matrix)))
if col_sum != original_colSum[j]:
return False, f"Column {j} sum mismatch"
return True, "Matrix is valid"
# Verify our solution
rowSum = [13, 14, 12]
colSum = [9, 13, 17]
result = solve(rowSum, colSum)
is_valid, message = verify_matrix(result, rowSum, colSum)
print(f"Verification: {message}")
Verification: Matrix is valid
Conclusion
This greedy approach efficiently constructs a valid matrix by always selecting the minimum remaining sum. The algorithm guarantees a solution exists when the total of row sums equals the total of column sums.
