All problems

Problem 364

Search a Sorted 2D Matrix

Medium · 20 pts · Matrix, Binary Search

Problem

An R x C matrix is sorted so that each row is in increasing order and the first value of every row is greater than the last value of the previous row. Read row by row, the whole matrix is one sorted list. Decide whether a target value T appears in the matrix. Treating the matrix as a single sorted array of R · C elements lets one binary search answer this in O(log(R · C)).

Input

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

Output

Print YES if T is in the matrix, otherwise NO.

Constraints

1 <= R, C <= 1000; -10000 <= value, T <= 10000

Example input

3 4 3
1 3 5 7
10 11 16 20
23 30 34 60

Example output

YES

Explanation

Reading the rows 1 3 5 7, 10 11 16 20 and 23 30 34 60 in order gives one sorted list, and 3 is in it, so the answer is YES.

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

Previous: Smallest Divisor Given a Threshold Next: Find K Closest Elements