Set matrix zeros


#1

PLEASE CHECK IF THIS APPROACH IS RIGHT!

public class Solution {
public void setZeroes(ArrayList<ArrayList> a) {
HashSet set=new HashSet<>();
for(int i=0;i<a.size();i++){
for(int j=0;j<a.get(0).size();j++){
if(a.get(i).get(j)==0){
set.add(i);
set.add(j);
}
}
}

    for(int i=0;i<a.size();i++){
        for(int j=0;j<a.get(0).size();j++){
            if(set.contains(i)||set.contains(j))
            a.get(i).set(j,0);
        }
    }
    
    System.out.println(a);
    
        
    
    
    
    
}

}


#2

This will fail for test case {{1,0},{1,1}}. As it will check for i=0 or j=1 and will return {{0,0},{0,0}}
Minor correction:

public void setZeroes(ArrayList<ArrayList> a) {
HashSet set1 = new HashSet<>();
HashSet set2 = new HashSet<>();
for (int i = 0; i < a.size(); i++) {
for (int j = 0; j < a.get(0).size(); j++) {
if (a.get(i).get(j) == 0) {
set1.add(i);
set2.add(j);
}
}
}

		for (int i = 0; i < a.size(); i++) {
			for (int j = 0; j < a.get(0).size(); j++) {
				if (set1.contains(i) || set2.contains(j))
					a.get(i).set(j, 0);
			}
		}  
                    System.out.println(a);     
}