Microsoft Interview: transforming a matrix

后端 未结 5 1987
伪装坚强ぢ
伪装坚强ぢ 2021-01-30 11:37

Given a matrix of size n x m filled with 0\'s and 1\'s

e.g.:

1 1 0 1 0

0 0 0 0 0

0 1 0 0 0

1 0 1 1 0

if the matrix has 1 a

5条回答
  •  傲寒
    傲寒 (楼主)
    2021-01-30 12:38

    Here is a solution in python pseudocode that uses 2 extra bools of storage. I think it is more clear than I could do in English.

    def scanRow(i):
        return 0 if row i is all zeroes, else 1
    
    def scanColumn(j):
        return 0 if col j is all zeroes, else 1
    
    # we're going to use the first row and column
    # of the matrix to store row and column scan values,
    # but we need aux storage to deal with the overlap
    firstRow = scanRow(0)
    firstCol = scanCol(0)
    
    # scan each column and store result in 1st row - O(mn) work
    for col in range(1, n):
        matrix[0, col] = scanColumn(col)
    
    # now row 0 tells us whether each column is all zeroes or not
    # it's also the correct output unless row 0 contained a 1 originally
    
    # do the same for rows into column 0 - O(mn) work
    for row in range(1, m):
        matrix[row, 0] = scanRow(row)
    
    matrix[0,0] = firstRow or firstCol
    
    # now deal with the rest of the values - O(mn) work
    for row in range(1, m):
        for col in range(1, n):
            matrix[row, col] = matrix[0, col] or matrix[row, 0]
    
    
    # 3 O(mn) passes!
    
    # go back and fix row 0 and column 0
    if firstRow:
        # set row 0 to all ones
    
    if firstCol:
        # set col 0 to all ones
    

提交回复
热议问题