Skip to content

Instantly share code, notes, and snippets.

@charlespunk
Created March 3, 2013 23:56
Show Gist options
  • Save charlespunk/5078962 to your computer and use it in GitHub Desktop.
Save charlespunk/5078962 to your computer and use it in GitHub Desktop.
Given a M*N matrix, if matrix[i][j] == 0, set all the elements in row i and column j to '0'.
When you could not use other buffer.
When this is a 3D matrix or nD matrix.
public static void setZeros(int[][] matrix){
int[] row = new int[matrix.length];
int[] column = new int[matirx[0].length];
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matirx[0].length; j++){
if(matrix[i][j] == 0){
row[i] = 0;
colum[j] = 0;
}
}
}
for(int i = 0; i < matrix.length; i++){
for(int j = 0; j < matirx[0].length; j++){
if(row[i] == 0 || column[j] == 0) row[i][j] = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment