Problem 491
Search a Row-Column Sorted Matrix
Medium · 20 pts · Matrix, Binary Search, Divide and Conquer
Problem
In an R x C matrix, every row is sorted in non-decreasing order from left to right and every column is sorted in non-decreasing order from top to bottom. Unlike a fully sorted matrix, a row's last element may be larger than the next row's first element. Decide whether a target T appears in the matrix. Start at the top-right corner: if the value is larger than T, move left; if smaller, move down. This takes O(R + C) steps.
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 <= 300; -1000000000 <= value, T <= 1000000000
Example input
5 5 5 1 4 7 11 15 2 5 8 12 19 3 6 9 16 22 10 13 14 17 24 18 21 23 26 30
Example output
YES
Explanation
Starting at 15 in the top-right corner while searching for 5: 15 > 5 moves left to 11, then 7, then 4 < 5 moves down to 5, which is the target. So the answer is YES.