Count Zeros in a Matrix
Count how many zeros are present in a matrix.
Sample input
[[1,0,3],[0,5,0],[7,0,9]]
Sample output
4
Solution
matrix = [[1, 0, 3], [0, 5, 0], [7, 0, 9]]
count = sum(row.count(0) for row in matrix)
print(count)
const matrix = [[1, 0, 3], [0, 5, 0], [7, 0, 9]];
let count = 0;
for (const row of matrix) {
for (const x of row) {
if (x === 0) count++;
}
}
console.log(count);
public class Main {
public static void main(String[] args) {
int[][] matrix = {{1, 0, 3}, {0, 5, 0}, {7, 0, 9}};
int count = 0;
for (int[] row : matrix) {
for (int x : row) {
if (x == 0) count++;
}
}
System.out.println(count);
}
}
fun main() {
val matrix = arrayOf(intArrayOf(1, 0, 3), intArrayOf(0, 5, 0), intArrayOf(7, 0, 9))
val count = matrix.sumOf { row -> row.count { it == 0 } }
println(count)
}
let matrix = [[1, 0, 3], [0, 5, 0], [7, 0, 9]]
let count = matrix.reduce(0) { $0 + $1.filter { $0 == 0 }.count }
print(count)
void main() {
final matrix = [[1, 0, 3], [0, 5, 0], [7, 0, 9]];
int count = 0;
for (final row in matrix) {
for (final x in row) {
if (x == 0) count++;
}
}
print(count);
}
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<vector<int>> matrix = {{1, 0, 3}, {0, 5, 0}, {7, 0, 9}};
int count = 0;
for (auto& row : matrix) {
for (int x : row) {
if (x == 0) count++;
}
}
cout << count << endl;
return 0;
}
#include <stdio.h>
int main() {
int matrix[3][3] = {{1, 0, 3}, {0, 5, 0}, {7, 0, 9}};
int count = 0;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (matrix[i][j] == 0) count++;
}
}
printf("%d\n", count);
return 0;
}