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