Skip to content

Commit b4f0e1a

Browse files
committed
Add Zero Striping
1 parent ae5b737 commit b4f0e1a

File tree

2 files changed

+86
-0
lines changed

2 files changed

+86
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
fun zeroStriping(matrix: MutableList<MutableList<Int>>) {
2+
if (matrix.isEmpty() || matrix[0].isEmpty()) {
3+
return
4+
}
5+
val m = matrix.size
6+
val n = matrix[0].size
7+
// Check if the first row initially contains a zero.
8+
var firstRowHasZero = false
9+
for (c in 0 until n) {
10+
if (matrix[0][c] == 0) {
11+
firstRowHasZero = true
12+
break
13+
}
14+
}
15+
// Check if the first column initially contains a zero.
16+
var firstColHasZero = false
17+
for (r in 0 until m) {
18+
if (matrix[r][0] == 0) {
19+
firstColHasZero = true
20+
break
21+
}
22+
}
23+
// Use the first row and column as markers. If an element in the
24+
// submatrix is zero, mark its corresponding row and column in the
25+
// first row and column as 0.
26+
for (r in 1 until m) {
27+
for (c in 1 until n) {
28+
if (matrix[r][c] == 0) {
29+
matrix[0][c] = 0
30+
matrix[r][0] = 0
31+
}
32+
}
33+
}
34+
// Update the submatrix using the markers in the first row and
35+
// column.
36+
for (r in 1 until m) {
37+
for (c in 1 until n) {
38+
if (matrix[0][c] == 0 || matrix[r][0] == 0) {
39+
matrix[r][c] = 0
40+
}
41+
}
42+
}
43+
// If the first row had a zero initially, set all elements in the
44+
// first row to zero.
45+
if (firstRowHasZero) {
46+
for (c in 0 until n) {
47+
matrix[0][c] = 0
48+
}
49+
}
50+
// If the first column had a zero initially, set all elements in
51+
// the first column to zero.
52+
if (firstColHasZero) {
53+
for (r in 0 until m) {
54+
matrix[r][0] = 0
55+
}
56+
}
57+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
fun zeroStripingHashSets(matrix: MutableList<MutableList<Int>>) {
2+
if (matrix.isEmpty() || matrix[0].isEmpty()) {
3+
return
4+
}
5+
val m = matrix.size
6+
val n = matrix[0].size
7+
val zeroRows = hashSetOf<Int>()
8+
val zeroCols = hashSetOf<Int>()
9+
// Pass 1: Traverse through the matrix to identify the rows and
10+
// columns containing zeros and store their indexes in the
11+
// appropriate hash sets.
12+
for (r in 0 until m) {
13+
for (c in 0 until n) {
14+
if (matrix[r][c] == 0) {
15+
zeroRows.add(r)
16+
zeroCols.add(c)
17+
}
18+
}
19+
}
20+
// Pass 2: Set any cell in the matrix to zero if its row index is
21+
// in 'zero_rows' or its column index is in 'zero_cols'.
22+
for (r in 0 until m) {
23+
for (c in 0 until n) {
24+
if (r in zeroRows || c in zeroCols) {
25+
matrix[r][c] = 0
26+
}
27+
}
28+
}
29+
}

0 commit comments

Comments
 (0)