Set Matrix Zeroes in swift

Question: – if on given matrix any element is zero set entire row & column to zero [Link]

func setZeroes(_ matrix: inout [[Int]]) {
    //Approach 2
    
    var matrixCount = matrix.count;
    var firstRowCount = matrix[0].count;
    var isCol = false
    for rowIndex in 0..<matrixCount {
        if matrix[rowIndex][0] == 0 {
            isCol = true
        }
        
        for colIndex in 1..<firstRowCount {
            if matrix[rowIndex][colIndex] == 0 {
                matrix[0][colIndex] = 0
                matrix[rowIndex][0] = 0
            }
        }
    }
    
    for rowIndex in 1..<matrixCount {
        for colIndex in 1..<firstRowCount {
            if (matrix[rowIndex][0] == 0) || ((matrix[0][colIndex] == 0)) {
                matrix[rowIndex][colIndex] = 0
            }
        }
    }
    
    if matrix[0][0] == 0 {
        for colIndex in 0..<firstRowCount {
            // Making cols to zero
            matrix[0][colIndex] = 0
        }
    }
    
    if isCol {
        for rowIndex in 0..<matrixCount {
            // Making rows to zero
            matrix[rowIndex][0] = 0
        }
    }
    
}
var matrixValue = [[1,1,1],[1,0,1],[1,1,1]]
setZeroes(&matrixValue)
print(matrixValue)
//Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
//Output: [[1,0,1],[0,0,0],[1,0,1]]
Approach #2

 Here we find the rows & cols which is zero & then iterate over matrix & make that rows and cols as zero

// Time Complexity: O(M×N) where M and N are the number of rows and columns respectively.
// Space Complexity: O(M + N).
// This is taking extra space because of storage of rows & cols.
func setZeroes(_ matrix: inout [[Int]]) {
    
    var cacheRows: [Int] = []
    var cacheCols: [Int] = []
    
    for i in 0..<matrix.count {
        for j in 0..<matrix[i].count {
            // Set Rows Cols index cache
            if matrix[i][j] == 0 {
                cacheRows.append(i)
                cacheCols.append(j)
            }
        }
    }
    
    
    for i in 0..<matrix.count {
        for j in 0..<matrix[i].count {
            // Set matrix to zero where it contains i Row & j Col
            if cacheRows.contains(i) || cacheCols.contains(j) {
                matrix[i][j] = 0
            }
        }
    }
}
var matrixArr1 = [[1,1,1],[1,0,1],[1,1,1]]
var matrixArr2 = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
setZeroes(&matrixArr1)
setZeroes(&matrixArr2)
print("matrix1 array-->", matrixArr1) // [[1, 0, 1], [0, 0, 0], [1, 0, 1]]
print("matrix2 array-->", matrixArr2) // [[0, 0, 0, 0], [0, 4, 5, 0], [0, 3, 1, 0]]

Leave a Comment

Your email address will not be published. Required fields are marked *