在 Python 中查找给定行和列总和的有效矩阵的程序
假设我们有两个非负值数组rowSum和colSum,其中rowSum[i]是第i行元素的总和,colSum[j]是二维矩阵第j列元素的总和。我们必须找到满足给定rowSum和colSum值的具有非负大小值(rowSumsizexcolSumsize)的任何矩阵。
因此,如果输入类似于rowSum=[13,14,12]colSum=[9,13,17],那么输出将是
示例
让我们看看以下实现以获得更好的理解-
def solve(r, c): matrix = [[0]*len(c) for _ in range(len(r))] visited = set() def minimum(r,c): min_total = float('inf') type = '' for i in range(len(r)): if(r[i] < min_total): index = i type = 'row' min_total = r[i] for i in range(len(c)): if(c[i] < min_total): min_total = c[i] type = 'col' index = i if(type == '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 if(type == '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)) while len(visited) != len(r)+len(c): minimum(r,c) return matrix rowSum = [13,14,12] colSum = [9,13,17] print(solve(rowSum, colSum))
输入
[13,14,12], [9,13,17]输出结果
[[9, 4, 0], [0, 9, 5], [0, 0, 12]]