2482. Difference Between Ones and Zeros in Row and Column
You are given a 0-indexed m x n binary matrix grid.
A 0-indexed m x n difference matrix diff is created with the following procedure:
- Let the number of ones in the
ithrow beonesRowi. - Let the number of ones in the
jthcolumn beonesColj. - Let the number of zeros in the
ithrow bezerosRowi. - Let the number of zeros in the
jthcolumn bezerosColj. diff[i][j] = onesRowi + onesColj - zerosRowi - zerosColj
Return the difference matrix diff.
pub fn ones_minus_zeros(grid: Vec<Vec<i32>>) -> Vec<Vec<i32>> {
let mut rows = vec![0; grid.len()];
let mut cols = vec![0; grid[0].len()];
let mut ans = vec![vec![0; grid[0].len()]; grid.len()];
for r in 0..grid.len() {
for c in 0..grid[0].len() {
rows[r] += grid[r][c];
cols[c] += grid[r][c];
}
}
for r in 0..grid.len() {
for c in 0..grid[0].len() {
ans[r][c] = rows[r] - (grid.len() as i32 - rows[r]) + cols[c] - (grid[0].len() as i32 - cols[c]);
}
}
ans
}