Search in two-dimensional array

Source: Internet
Author: User

In a two-dimensional array, each row is sorted in ascending order from left to right, and each column is sorted in ascending order from top to bottom. Complete a function, input a two-dimensional array and an integer to determine whether the array contains the integer. Input: the input may contain multiple test examples. For each test case, the first input behavior is two integers, m and n (1 <= m, n <= 1000 ): the number of rows and columns of the matrix to be input. The second line of the input contains an integer t (1 <= t <= 1000000): the number to be searched. In the next m row, each row has n numbers, representing the matrix of n columns in the m row given by the question (the matrix is shown in the description of the question, and each row is sorted in ascending order from left to right, each column is sorted in ascending order from top to bottom. Output: For each test case, "Yes" indicates that the number t is found in the two-dimensional array. The output "No" indicates that the number t is not found in the two-dimensional array. Sample input: 3 351 2 34 5 67 8 93 312 3 45 6 78 9 103 3122 3 45 6 78 9 10 sample output: YesNoNo code AC: idea: query X from the upper right corner. If the current number is greater than X, it moves to the left. If it is less than X, it moves down! [Cpp] # include <stdio. h> int main () {int mat [1000] [1000], I, j, m, n, t, flag; while (scanf ("% d ", & m, & n )! = EOF) {scanf ("% d", & t); for (I = 0; I <m; I ++) {for (j = 0; j <n; j ++) {scanf ("% d", & mat [I] [j]) ;}} I = 0; // top right vertex j = n-1; flag = 0; while (I <m & j> = 0) {if (mat [I] [j] <t) {I ++ ;} else if (mat [I] [j]> t) {j --;} else {flag = 1; break ;}} if (flag) {printf ("Yes \ n") ;}else {printf ("No \ n") ;}} return 0 ;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.