How to change all elements of row i and column j in a binary matrix to 0 if cell[i, j] is 0 in Swift

1 Answer

0 votes
import Foundation

func changeRowColumn(matrix: inout [[Int]], row: Int, col: Int) {
    let rows = matrix.count
    let cols = matrix[0].count

    for j in 0..<cols {
        if matrix[row][j] != 0 {
            matrix[row][j] = -1
        }
    }

    for i in 0..<rows {
        if matrix[i][col] != 0 {
            matrix[i][col] = -1
        }
    }
}

func changeBinaryMatrix(matrix: inout [[Int]]) {
    let rows = matrix.count
    guard rows > 0 else { return }
    let cols = matrix[0].count
    guard cols > 0 else { return }

    var zeroPositions = [(Int, Int)]()

    for i in 0..<rows {
        for j in 0..<cols {
            if matrix[i][j] == 0 {
                zeroPositions.append((i, j))
            }
        }
    }

    for (row, col) in zeroPositions {
        changeRowColumn(matrix: &matrix, row: row, col: col)
    }

    for i in 0..<rows {
        for j in 0..<cols {
            if matrix[i][j] == -1 {
                matrix[i][j] = 0
            }
        }
    }
}

func printMatrix(matrix: [[Int]]) {
    for row in matrix {
        print(row.map { String($0) }.joined(separator: " "))
    }
}

var matrix = [
    [1, 1, 0, 1, 1, 1],
    [1, 1, 1, 1, 1, 1],
    [1, 1, 0, 1, 1, 1],
    [1, 1, 1, 1, 1, 1],
    [1, 0, 1, 1, 1, 1]
]

changeBinaryMatrix(matrix: &matrix)
printMatrix(matrix: matrix)



/*
run:

0 0 0 0 0 0
1 0 0 1 1 1
0 0 0 0 0 0
1 0 0 1 1 1
0 0 0 0 0 0

*/

 



answered Jul 5 by avibootz
...