Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Created LeetCode73 Set Matrix Zeros (Medium) #369 #458

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions LeetCode Problems/_73_SetMatrixZeros.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
package githubpr;

import java.util.Arrays;

/*
time n2
space constant (changing in place)
*/
public class _73_SetMatrixZeros {
public void setZeroes(int[][] matrix) {
matrixZeros(matrix);
}
public void matrixZeros(int[][] arr){
boolean firstCol=false,firstRow=false;

//Step 1 : check for zeros and mark in the first row/col
for(int i=0;i<arr.length;i++){
for (int j=0;j<arr[0].length;j++){
if(arr[i][j]==0){
if (j==0) firstCol=true;
if (i==0) firstRow=true;
arr[i][0]=0;
arr[0][j]=0;
}
}
}

//Step 2 : make rows and cols zeros if they have a zero, except first row/col
for(int i=1;i<arr.length;i++){
for(int j=1;j<arr[0].length;j++){
if(arr[i][0]==0 || arr[0][j]==0){
arr[i][j]=0;
}
}
}

//Step 3 : making the firstrow and firstcol zero if required

//atleast one element is zero in the first row :- therefore making all zero
if(firstRow){
Arrays.fill(arr[0], 0);

}

//atleast one element is zero in the first col :- therefore making all zero
if(firstCol){
for(int i=0;i<arr.length;i++){
arr[i][0]=0;
}
}
}
}