Leetcode-Solutions

My Leetcode Solutions.

View on GitHub

73. Set Matrix Zeroes

Topics: Array Hash Table Matrix

Solution 1

Implementation

class Solution {
    fun setZeroes(matrix: Array<IntArray>): Unit {
        val height = matrix.size
        val width = matrix[0].size

        val heightZeros = mutableListOf<Int>()
        val widthZeros = mutableListOf<Int>()

        for (i in 0 until height) {
            for (j in 0 until width) {
                if (matrix[i][j] == 0) {
                    heightZeros.add(i)
                    widthZeros.add(j)
                }
            }
        }

        for (i in heightZeros) {
            for (j in 0 until width) {
                matrix[i][j] = 0
            }
        }

        for (j in widthZeros) {
            for (i in 0 until height) {
                matrix[i][j] = 0
            }
        }
    }
}

Solution 2

Implementation

class Solution {
    fun setZeroes(matrix: Array<IntArray>): Unit {
        val height = matrix.size
        val width = matrix[0].size

        var firstColHasZero = false
        var firstRowHasZero = false

        for (i in 0 until height) {
            if (matrix[i][0] == 0) {
                firstColHasZero = true
                break
            }
        }

        for (j in 0 until width) {
            if (matrix[0][j] == 0) {
                firstRowHasZero = true
                break
            }
        }

        for (i in 1 until height) {
            for (j in 1 until width) {
                if (matrix[i][j] == 0) {
                    matrix[i][0] = 0
                    matrix[0][j] = 0
                }
            }
        }

        for (i in 1 until height) {
            if (matrix[i][0] != 0) continue
            for (j in 1 until width) {
                matrix[i][j] = 0
            }
        }

        for (j in 1 until width) {
            if (matrix[0][j] != 0) continue
            for (i in 1 until height) {
                matrix[i][j] = 0
            }
        }

        if (firstColHasZero) {
            for (i in 0 until height) {
                matrix[i][0] = 0
            }
        }

        if (firstRowHasZero) {
            for (j in 0 until width) {
                matrix[0][j] = 0
            }
        }
    }
}