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]]