GivenMXNMatrix, if an element is 0, set its entire row and column to 0. Do it in place.
Click to show follow up.
Follow up:
Did you use extra space?
A straight forward solution using O (MN) Space is probably a bad idea.
A simple improvement Uses O (M+N) Space, but still not the best solution.
Cocould you devise a constant space solution?
1 Public Class Solution { 2 Public Void Setzeroes ( Int [] [] Matrix ){ 3 If (Matrix = Null | Matrix. Length = 0 | matrix [0]. Length = 0) Return ; 4 Int Row = 0, Col = 0 ; 5 Boolean Sig = True ; 6 For ( Int I = 0; I <matrix. length; I ++ ){ 7 For ( Int J = 0; j <matrix [0]. length; j ++ ){ 8 If (Matrix [I] [J] = 0 ){ 9 If (SIG ){ 10 Row = I; 11 Col = J; 12 Sig = False ; 13 } Else { 14 Matrix [row] [J] = 0 ; 15 Matrix [I] [col] = 0 ; 16 } 17 } 18 } 19 } 20 If (SIG) Return ; 21 For (Int I = 0; I <matrix. length; I ++ ){ 22 For ( Int J = 0; j <matrix [0]. length; j ++ ){ 23 If (Matrix [row] [J] = 0 | matrix [I] [col] = 0) & I! = Row & J! = Col) matrix [I] [J] = 0 ; 24 } 25 } 26 For ( Int I = 0; I <matrix. length; I ++ ){ 27 Matrix [I] [col] = 0 ; 28 } 29 For ( Int J = 0; j <matrix [0]. length; j ++ ){ 30 Matrix [row] [J] = 0 ; 31 } 32 } 33 }
Set matrix zeroes