假设我们有一个二维数字矩阵,现在针对给定矩阵中的每个零,并将其行和列中的所有值替换为零,然后返回最终矩阵。
因此,如果输入就像矩阵,那么输出将是矩阵,因为第0、2和3行包含0,而最后的矩阵在这些行中包含0。类似地,第0列,第1列和第2列包含0,而这些列中的最终矩阵包含0。
为了解决这个问题,我们将按照以下步骤操作:
n := row count, m := column count res := make a matrix of size n x m and fill with 0 transpose := transpose given matrix for each row i, do if 0 not in matrix[i], then for each column j in matrix, do if 0 not in transpose[j], then res[i, j] := matrix[i, j] return res
让我们看下面的实现以更好地理解-
class Solution: def solve(self, matrix): n, m = len(matrix), len(matrix[0]) res = [[0 for __ in range(m)] for _ in range(n)] transpose = [list(row) for row in zip(*matrix)] for i in range(n): if 0 not in matrix[i]: for j in range(m): if 0 not in transpose[j]: res[i][j] = matrix[i][j] return res ob = Solution()matrix = [ [6, 0, 0, 6, 9], [4, 9, 9, 4, 8], [0, 8, 3, 4, 2], [9, 0, 7, 8, 3], [5, 2, 9, 6, 8] ] print(ob.solve(matrix))
matrix = [ [6, 0, 0, 6, 9], [4, 9, 9, 4, 8], [0, 8, 3, 4, 2], [9, 0, 7, 8, 3], [5, 2, 9, 6, 8] ]
输出结果
[[0, 0, 0, 0, 0], [0, 0, 0, 4, 8], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 6, 8]]