-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSetMatrixZeroes.kt
More file actions
55 lines (47 loc) · 1.44 KB
/
SetMatrixZeroes.kt
File metadata and controls
55 lines (47 loc) · 1.44 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
package leetcode
/**
* Problem description on [LeetCode](https://leetcode.com/problems/set-matrix-zeroes/)
*/
class SetMatrixZeroes {
fun setZeroes(matrix: Array<IntArray>) {
val zeroInFirstRow = firstRowContainsZero(matrix)
val zeroInFirstCol = firstColContainsZero(matrix)
for (row in 1 until matrix.size) {
for (col in 1 until matrix[0].size) {
if (matrix[row][col] == 0) {
matrix[row][0] = 0
matrix[0][col] = 0
}
}
}
for (row in 1 until matrix.size) {
for (col in 1 until matrix[0].size) {
if (matrix[row][0] == 0 || matrix[0][col] == 0) {
matrix[row][col] = 0
}
}
}
if (zeroInFirstRow) {
for (col in matrix[0].indices) {
matrix[0][col] = 0
}
}
if (zeroInFirstCol) {
for (row in matrix.indices) {
matrix[row][0] = 0
}
}
}
private fun firstRowContainsZero(matrix: Array<IntArray>): Boolean {
for (col in matrix[0].indices) {
if (matrix[0][col] == 0) return true
}
return false
}
private fun firstColContainsZero(matrix: Array<IntArray>): Boolean {
for (row in matrix.indices) {
if (matrix[row][0] == 0) return true
}
return false
}
}