All problems

Problem 380

Count Negatives in a Sorted Matrix

Easy · 10 pts · Matrix, Binary Search

Problem

Every row and every column of an R x C matrix is sorted in non-increasing order (values only stay the same or go down as you move right or down). Count the negative numbers in the matrix. Checking every cell is O(R · C); starting from the bottom-left corner and walking up or right uses the sorted order to finish in O(R + C).

Input

First line: R and C. Next R lines: C integers each.

Output

Print the number of negative values.

Constraints

1 <= R, C <= 1000; -100 <= value <= 100

Example input

4 4
4 3 2 -1
3 2 1 -1
1 1 -1 -2
-1 -1 -2 -3

Example output

8

Explanation

The matrix 4 3 2 -1 / 3 2 1 -1 / 1 1 -1 -2 / -1 -1 -2 -3 contains 8 negative numbers.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Integer Nth Root Next: Delete the Middle Node