object BinaryMatrixTransformer {
def changeRowColumn(matrix: Array[Array[Int]], row: Int, col: Int): Unit = {
val rows = matrix.length
val cols = matrix(0).length
for (j <- 0 until cols) {
if (matrix(row)(j) != 0)
matrix(row)(j) = -1
}
for (i <- 0 until rows) {
if (matrix(i)(col) != 0)
matrix(i)(col) = -1
}
}
def changeBinaryMatrix(matrix: Array[Array[Int]]): Unit = {
val rows = matrix.length
if (rows == 0) return
val cols = matrix(0).length
if (cols == 0) return
// First pass: mark positions
val zeroPositions = for {
i <- 0 until rows
j <- 0 until cols
if matrix(i)(j) == 0
} yield (i, j)
// Apply changes
zeroPositions.foreach { case (i, j) => changeRowColumn(matrix, i, j) }
// Second pass: clean up -1 placeholders
for (i <- 0 until rows; j <- 0 until cols) {
if (matrix(i)(j) == -1)
matrix(i)(j) = 0
}
}
def printMatrix(matrix: Array[Array[Int]]): Unit = {
matrix.foreach { row =>
println(row.mkString(" "))
}
}
def main(args: Array[String]): Unit = {
val matrix = Array(
Array(1, 1, 0, 1, 1, 1),
Array(1, 1, 1, 1, 1, 1),
Array(1, 1, 0, 1, 1, 1),
Array(1, 1, 1, 1, 1, 1),
Array(1, 0, 1, 1, 1, 1)
)
changeBinaryMatrix(matrix)
printMatrix(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
*/