Microsoft Interview: transforming a matrix

后端 未结 5 1984
伪装坚强ぢ
伪装坚强ぢ 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:32

    Assuming matrix is 0-based, i.e. the first element is at mat[0][0]

    1. Use the first row and first column as table headers to contain column and row info respectively. 1.1 Note the element at mat[0][0]. If it is 1, it will require special handling at the end (described later)

    2. Now, start scanning the inner matrix from index[1][1] up to the last element 2.1 If the element at[row][col] == 1 then update the table header data as follows Row: mat[row][0] = 1; Column: mat[0][col] = 1;

    At this point we have the complete info on which column and row should be set to 1

    1. Again start scanning the inner matrix starting from mat[1][1] and set each element to 1 if either the current row or column contains 1 in the table header: if ( (mat[row][0] == 1) || (mat[0][col] == 1) ) then set mat[row][col] to 1.

    At this point we have processed all the cells in the inner matrix and we are yet to process the table header itself

    1. Process the table header If the matt[0][0] == 1 then set all the elements in the first column and first row to 1
    2. Done

    Time complexity O(2*((n-1)(m-1)+(n+m-1)), i.e. O(2*n*m - (n+m) + 1), i.e. O(2*n*m) Space O(1)

    See my implementation at http://codepad.org/fycIyflw

提交回复
热议问题