DEV Community

Cover image for Cells with Odd Values in a Matrix(LeetCode-easy)
Tahzib Mahmud Rifat
Tahzib Mahmud Rifat

Posted on

Cells with Odd Values in a Matrix(LeetCode-easy)

INTRODUCTION

Image description

We, have given two array one is main array matrix and other is indices[is a 2D array]. Each indices value consist two things one is row value and another is column value, indices[i] = [ri, ci]. And our task is to simply increment by 1 the whole row and whole column.

NOTE: Because indices is 2D array, so we can easily get the row value using row = indices[i][0] , and the column value using col = indices[i][1]

Examples

Image description

Hints

Image description


Steps

  1. Create an array of size m, n
  2. Set the row value and col value from indices
  3. Increment the whole row and col by 1
  4. Check the main matrix values for ODD number.
  5. Return the counter.

Java Code

class Solution {
    public int oddCells(int m, int n, int[][] indices) {
        int[][] mat = new int[m][n];
        for (int i = 0; i < indices.length; i++) {
            int row = indices[i][0];
            int col = indices[i][1];

            for (int j = 0; j <n; j++) {
                mat[row][j]++;
            }
            for (int j = 0; j <m; j++) {
                mat[j][col]++;
            }
        }

        int count = 0;
        for (int i = 0; i <m; i++) {
            for (int j = 0; j < n; j++) {
                if(mat[i][j] % 2 != 0){
                    count++;
                }
            }
        }
        return count;
    }
}
Enter fullscreen mode Exit fullscreen mode

Output

Image description

Top comments (0)

Great read:

Is it Time to go Back to the Monolith?

History repeats itself. Everything old is new again and I’ve been around long enough to see ideas discarded, rediscovered and return triumphantly to overtake the fad. In recent years SQL has made a tremendous comeback from the dead. We love relational databases all over again. I think the Monolith will have its space odyssey moment again. Microservices and serverless are trends pushed by the cloud vendors, designed to sell us more cloud computing resources.

Microservices make very little sense financially for most use cases. Yes, they can ramp down. But when they scale up, they pay the costs in dividends. The increased observability costs alone line the pockets of the “big cloud” vendors.