Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,641 questions

55,376 answers

573 users

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, 2025 by avibootz
...