Count Negative Numbers in a Sorted Matrix

Count Negative Numbers in a Sorted Matrix

Q - Given a m x n matrix grid which is sorted in non-increasing order both row-wise and column-wise, return the number of negative numbers in grid.

LeetCode Problem: Link | Click Here

class Solution {
    public int countNegatives(int[][] grid) {
        // Get the length of rows and columns in the grid

        int rowLen = grid.length; // Number of rows
        int colLen = grid[0].length; // Number of columns in the first row (assuming all rows have the same number of columns)
        int count = 0; // Initialize the count of negative numbers

        // Loop through each row
        for(int i = 0; i < rowLen; i++){ // i = row, j = column
            // Loop through each column in the current row
            for (int j = 0; j < colLen; j++){
                // Check if the current element is negative
                if (grid[i][j] < 0){
                    count++; // Increment count if the element is negative
                }
            }
        }
        return count; // Return the total count of negative numbers in the grid
    }
}