Given a matrix if an element in the matrix is 0 then you will have to set its entire column and row to 0 and then return the matrix.
This is one of the problems which is asked in interviews. So lets see how to solve it.
First of all we will think about the approach :
Most important thing is to store the indexes where 0 exists.
Approach 1 : Brute force means trying every possible case without using any Data structure. And if we will do something like this then that code will not make any sense as it will not be cleaner.
Approach 2 : Using LinkedList or ArrayList to store the indexes and based on those indexes we will assign zero on that particular row and column.
Note : we can't use HashMap or HashSet because the there could be multiple zeroes on same row or column that's why key can collide in Hash family DS.
Java code for setZeroes problem :
class Solution {
public void setZeroes(int[][] matrix) {
ArrayList<Integer> list1=new ArrayList<>();
ArrayList<Integer> list2=new ArrayList<>();
for(int i=0;i<matrix.length;i++)
{
for(int j=0;j<matrix[i].length;j++)
{
if(matrix[i][j]==0) {
list1.add(i);
list2.add(j);
}
}
}
for(int e=0;e<list1.size();e++)
{
int i=list1.get(e);
int j=list2.get(e);
System.out.println(i+" "+j);
for(int a=0;a<matrix[i].length;a++) matrix[i][a]=0;
for(int a=0;a<matrix.length;a++) matrix[a][j]=0;
}
}
}
Comments
Post a Comment