Flashcards
Set Matrix Zeroes
Cards in this deck (1)
- 1Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place. [ [1,1,1], [1,0,1], [1,1,1] ] Output: [ [1,0,1], [0,0,0], [1,0,1] ]public void setZeroes(int[][] matrix) {
int rows = matrix.length;
int cols = matrix[0].length;
int col = 1;
for( int i = 0; i < rows ; i++ ){
if( matrix[i][0] == 0 ){
col = 0;
}
for(int j = 1; j < cols ; j++ ){
if( matrix[i][j] == 0 ){
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for( int i = rows - 1; i >=0; i-- ){
for( int j = cols - 1; j >=1; j-- ){
if( matrix[i][0] == 0 || matrix[0][j] == 0 ){
matrix[i][j] = 0;
}
}
if( col == 0 ){
matrix[i][0] = 0;
}
}
}
Information
- Description
- Flashcards on Set Matrix Zeroes, created by Suhas S on 01/06/2018.
- Created by
- Suhas S · Jun 2018
- Updated
- Jun 1, 2018
- Views
- 1
- Rating