# Cells with Odd Values in a Matrix in C++

C++Server Side ProgrammingProgramming

Suppose there are n and m which are the dimensions of a matrix. These are initialized by zeros. And indices are given where indices[i] = [ri, ci]. For each pair of [ri, ci] we have to increment all cells in row ri and column ci by 1. The output will be the number of cells with odd values in the matrix after applying the increment to all indices.

To solve this, we will follow these steps −

• Initialize odd := 0, and x := row count of the matrix
• create a matrix mat
• for i in range 0 to x
• r = input[i, 0], c = input[i, 1],
• for j in range 0 to m – 1
• mat[r, j] := mat[r, j] + 1
• for j in range 0 to n – 1
• mat[j, c] := mat[j, c] + 1
• for i in range 0 to n – 1
• for j := 0 to m – 1
• odd := odd + mat[i, j] bitwise or with 1
• return odd

## Example

Let us see the following implementation to get better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int oddCells(int n, int m, vector<vector<int>>& in) {
int odd = 0;
int x = in.size();
vector < vector <int> > mat(n, vector <int>(m));
for(int i = 0; i < x ;i++){
int r = in[i];
int c = in[i];
for(int j = 0; j < m; j++){
mat[r][j]++;
}
for(int j = 0; j < n; j++){
mat[j][c]++;
}
}
for(int i = 0; i < n; i++){
for(int j = 0; j < m; j++)odd += mat[i][j] & 1;
}
return odd;
}
};
main(){
Solution ob;
vector<vector<int>> c = {{0,1},{1,1}};
cout << ob.oddCells(2,3,c);
}

## Input

2
3
{{0,1},{1,1}}

## Output

6