Skip to content

Commit ef0ec66

Browse files
1 parent 64f91b1 commit ef0ec66

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

Diff for: SetMatrixZeros

+63
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import java.util.HashSet;
2+
import java.util.Set;
3+
public class SetMatrixElementsToZero
4+
{
5+
//function to set matrix elements to zero
6+
public static void setZero(int[][] array)
7+
{
8+
Set<Integer> rowsToZero = new HashSet<>();
9+
Set<Integer> columnsToZero = new HashSet<>();
10+
//loop iterate over rows
11+
for (int i = 0; i < array.length; i++)
12+
{
13+
//loop iterate over columns
14+
for (int j = 0; j < array.length; j++)
15+
{
16+
//compares an element is zero or not
17+
if (array[i][j] == 0)
18+
{
19+
//if the condition returns true add that element to set
20+
rowsToZero.add(i);
21+
columnsToZero.add(j);
22+
}
23+
}
24+
}
25+
//loop sets the corresponding row to zero
26+
for (int i : rowsToZero)
27+
{
28+
for (int j = 0; j < array.length; j++)
29+
{
30+
array[i][j] = 0;
31+
}
32+
}
33+
//loop sets the corresponding columns to zero
34+
for (int i : columnsToZero)
35+
{
36+
for (int j = 0; j < array.length; j++)
37+
{
38+
array[j][i] = 0;
39+
}
40+
}
41+
//loop for printing rows
42+
for (int i = 0; i < array.length; i++)
43+
{
44+
//loop for printing columns
45+
for (int j = 0; j < array.length; j++)
46+
{
47+
//prints matrix elements
48+
System.out.print(array[i][j]+"\t");
49+
if(j == array.length-1)
50+
//throws cursor to the next line
51+
System.out.println();
52+
}
53+
}
54+
}
55+
//driver code
56+
public static void main(String args[])
57+
{
58+
//an array whose rows and column set to be zero
59+
int[][] arr = { { 1, 0, 1, 1, 0 }, { 0, 1, 1, 1, 0 }, { 1, 1, 1, 1, 1 }, { 1, 0, 1, 1, 1 }, { 1, 1, 1, 1, 1 } };
60+
//function calling
61+
setZero(arr);
62+
}
63+
}

0 commit comments

Comments
 (0)